Reputation: 2071
We can use the below query to retrieve specific columns using Entity Framework:
var result = context.Contents.Where(c => c.CatalogId == "ABC")
.Select(c => new {c.ContentId, c.ContentName});
I want to pass the column names during runtime.
Can I pass these column names {c.ContentId, c.ContentName}
dynamically at runtime.
Thanks
Upvotes: 1
Views: 3382
Reputation:
You have to construct a lambda expression at runtime for that to work. There are libraries such as Dynamic LINQ that do some of the work for you, and the Expression APIs themselves aren't too bad to be honest, but I feel it becomes more effort than it is worth at that point. The simplest way is just to drop back down to plain parametrized SQL:
var fields = new[] { "ContentId", "ContentName" };
var q = "SELECT " + string.Join(", ", fields) + " WHERE CatalogId = @Id";
var result = context.Database.SqlQuery<dynamic>(q, new SqlParameter("Id", "ABC"));
Note: Be absolutely certain that the field names here are not coming from user input, because if you don't do that, you're opening yourself up to SQL injection. There are ways to contort the query a bit to avoid SQL injection (add a variable in the query that is parametrized, do a switch case on the variable to select fields), but that is beyond the scope of this answer. Best to entirely avoid interpolating strings from unknown sources into your SQL.
Upvotes: 3