dynamically pass column names to be selected at runtime in entity framework

c# entity-framework-6

Question

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

1
1
6/27/2015 5:06:29 PM

Popular Answer

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.

3
6/27/2015 5:27:23 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow