Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

c# - Converting List<string> to EntityFramework column/field list

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 strings (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 strings 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use dynamic linq, check it in here. It is also available on nuget


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...