3

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 ?
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
Ramesh Bolla
  • 372
  • 1
  • 3
  • 21
  • 1
    hmm... It's not clear what you need since the code you posted seems to answer your own question. can you be more specific? Do you want the returned objects to be of a specific type? Also unless you have some columns that store large amounts of data selecting fewer columns is unlikely to improve your performance noticeably. – Ben Tidman Jan 02 '13 at 12:47
  • Hi Ben Tidman, i need to build a select dynamic query with required fields. so i need to get dynamic code for .Select(p => new {id=p.Id, title=p.Title,pc=p.PostalCode }) using lamda expression or linq expressions no idea ! – Ramesh Bolla Jan 02 '13 at 13:52
  • If you're going to create the anonymous type dynamically (which seems to be what you want), how are you going to access its members? – svick Jan 02 '13 at 14:23

1 Answers1

1

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.

usr
  • 168,620
  • 35
  • 240
  • 369
  • Hi usr, i need to change .Select(p => new {id=p.Id, title=p.Title,pc=p.PostalCode }); with required fields. – Ramesh Bolla Jan 02 '13 at 13:49
  • @RameshBolla Look at the expression the C# compiler generated so that you learn how it looks like. You have to build an expression yourself that only contains the required fields. Use the `Expression` class. – usr Jan 02 '13 at 13:51