Using EntityFramework, I can get a list of entities of a certain type using the following syntax:
List<Customer> customers = ((IQueryable<Customer>)myEntities.Customers
.Where(c => c.Surname == strSurname)
.OrderBy(c => c.Surname)).ToList<Customer>();
I can then do something like this to end up with only the data I'm interested in:
var customerSummaries = from s in customers
select new
{
s.Surname, s.FirstName, s.Address.Postcode
};
I'm given a list of string
s (based on user selection) of the fields (and tables where necessary) that comprise the requested summarized data. Eg for the above 'customerSummary' the list of string
s provided would be: "Surname", "FirstName", "Address.Postcode".
My question is: How do I convert that list of strings into the syntax needed to extract only the specified fields?
If that can't be done, what would be a better type (than string) for the list of columns so I can extract the right info?
I guess I need to know the type that an EF [entity|table]'s [member|column|field] is, if that makes sense.
EDIT:
I tried the suggested answer - dynamic linq - using the following syntax
string parmList = "Surname, Firstname, Address.Postcode";
var customers = myEntities.Customers.Select(parmList)
.OrderBy("Address.Postcode");
but this results in: EntitySqlException was unhandled. 'Surname' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly.
So, a follow-up question. Am I using Select
properly? I have only seen examples using the Where
and OrderBy
clauses, but I think I'm doing it right based on those.
If my Select syntax is not the problem, can anyone see what is?
Edit 2: It was upside down. This works:
string parmList = "Surname, Firstname, Address.Postcode";
var customers = myEntities.Customers
.OrderBy("Address.Postcode")
.Select(parmList);
See Question&Answers more detail:
os