linq - Entity Framework Select new POCO without .ToList() first -
i'm creating application service layer (wcf website) , silverlight 4 client. ria services not option, create intermediary classes pass , forth. purpose of question let's assume i'm passing , forth tasty food
objects.
public class fooddata { public int id { get; set; } public string name { get; set; } public tastyness tastylevel { get; set; } }
the ef model same class, table 3 basic fields (the tastyness int corresponds our enum tastyness).
i find myself using kind of statement lot when doing entity framework queries:
public list<fooddata> getdeliciousfoods() { var deliciousfoods = entities.foods .where(f => f.tastyness == (int)tastyness.delicious) .tolist() // necessary? , if so, best performance list, array, other? .select(dfood => dfood.tofooddata()) .tolist(); return deliciousfoods; }
without .tolist() call exception linq not being able translate custom method query equivalent, understand.
my question call .tolist() before .select(...) custom extension convert our object poco version of food object.
is there better pattern here, or maybe better alternative .tolist() may more performant since don't require functionality of list<..> result.
the problem using tolist
or asenumerable
materialize entire entity , pay cost of fixup. if want have best possible sql returns needed fields, should project directly rather using .tofooddata()
:
var deliciousfoods = entities.foods .where(f => f.tastyness == (int)tastyness.delicious) .select(dfood => new fooddata { id = dfood.id, name = dfood.name, tastylevel = (tastyness)dfood.tastyness });
the cast enum may problem. if so, go through anonymous type:
var deliciousfoods = entities.foods .where(f => f.tastyness == (int)tastyness.delicious) .select(dfood => new fooddata { id = dfood.id, name = dfood.name, tastylevel = dfood.tastyness }) .asenumerable() .select(dfood => new fooddata { id = dfood.id, name = dfood.name, tastylevel = (tastyness)dfood.tastylevel });
if examine resulting sql, you'll see it's simpler, , don't pay cost of fixing objects objectcontext.
Comments
Post a Comment