2

OK. So maybe I am lazy. I don't want to new up an EF object and have to define all of the properties in my linq statement. This is easy unless you want to modify a property in this object. In this case, my supplier name property may change based on if the supplier is an agency or a independent contractor.

var results = db.tblSuppliers.Select(s => { s.SupplierName = s.CompanyName == null ? s.SupplierFirstName + " " + s.SupplierLastName : s.CompanyName; return s; });

return results.ToList<tblSupplier>();

I get the following error: A lambda expression with a statement body cannot be converted to an expression tree

I want to return this back as a list of supplier objects.

Steve3p0
  • 2,332
  • 5
  • 22
  • 30
  • Possible Duplicate: [“A lambda expression with a statement body cannot be converted to an expression tree”](http://stackoverflow.com/q/5179341/299327) – Ryan Gates Mar 08 '13 at 16:10

2 Answers2

2

You have to bring it into memory first and do the projection there - otherwise Linq to Entities will try to convert your projection into a SQL query, for which of course there is no equivalent. You can use AsEnumerable() to force the Select() projection to be executed in a Linq to Objects context which will then work:

var results = db.tblSuppliers
                .AsEnumerable()
                .Select(s => { s.SupplierName = s.CompanyName == null ? s.SupplierFirstName + " " + s.SupplierLastName : s.CompanyName; return s; })
                .ToList();

Second problem is that you cannot project to an entity with EF but using AsEnumerable() avoids this problem as well.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
2

Select is used for transformation operations. It looks like you just want to mutate the objects by setting the SupplierName for each element...

You could use List.ForEach to apply the property change you want:

var results = db.tblSuppliers.ToList();
results.ForEach(s => s.SupplierName = s.CompanyName == null ? s.SupplierFirstName + " " + s.SupplierLastName : s.CompanyName);
Reddog
  • 15,219
  • 3
  • 51
  • 63
  • Thank you. This works, but I realized I need to now join to other tables to get descriptions of the foreign keys in my table. So really what I want is something like "Select *, desc1, desc2 from table join foreign1... join foreign2. Now before all you SQL purist pile up on me and lash me for even thinking "select *", I would settle for something that would gen up all the properties I need like sql management studio does when it gens up all the columns in the "script table as.." feature. – Steve3p0 Nov 15 '11 at 23:58