I'm looking to create a method that does something like ConvertFieldNamesToSelect below, which would dynamically create the select expression from a string array of column names, but I'm not sure if it's possible?
using (var dc = new MyDataContext(myConnectionStr))
{
IQueryable<User> query = dc.Users.Where(u => u.UserID == 4);
List<User> users = query.Select(ConvertFieldNamesToSelect<User>(new string[] { "UserID", "Name" })).ToList();
return users;
}
I've seen threads like: LINQ : Dynamic select
Unfortunately they don't work correctly with Linq To Sql. At database level they either select all fields then refine afterwards (inefficent, visible via profiler) or throw an exception Explicit construction of entity type 'X' in query is not allowed because they are attempting to create an e.g. User() object in the query (rather than a dynamic object), which Linq To Sql doesn't allow, but regular Linq on lists does.
dc.ExecuteQuery(sql) could of course select the fields via a SQL statement, but that would mean IQueryable benefits are lost, and we have lots of existing code building those up dynamically. Would also consider DynamicLinq if that's an option.