Lambda Expression for LINQ Select Items

entity-framework lambda linq linq-to-entities

Question

I have this code

var list = _db.Projects.Where(item => item.Loc =="IN").Select(p => new {id=p.Id, title=p.Title,pc=p.PostalCode });

Project table having lot of columns, i need to query required columns dynamically and load from database, not all columns along with data.

Questions:

  1. how to write lambda expressions for linq select ?
  2. How to reduce data reads on database by selecting specific cols, entity framework ?
1
3
7/4/2017 7:47:12 AM

Accepted Answer

Look at the expression the C# compiler generated and try to replicate what it does:

Expression<Func<Project, object>> lambda =
    (Project p) => (object)new {id=p.Id, title=p.Title,pc=p.PostalCode };

I hope this code compiles. If not, you'll surely be able to fix it. Afterwards, look at the contents of the lambda variable.

Note, that the cast to object is only there to make this compile. You don't need/want that is production.

1
1/2/2013 1:28:44 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