开发者

Is it necessary to always Select()... new{Anon}... AsEnumerable...Select(new EntityType{}) every time?

I keep running into a pattern whereby I want to select rows from an Entit开发者_运维百科y Collection (EF4) and use the data to create new rows in a different entity collection.

The only way I have found to do this is to perform the following steps:

var newEntities = (from e in myentities
  where e.x == y
  select new {
    Prop1 = e.Prop1,
    Prop2 = e.Prop2+e.Prop3,
    Prop3 = DateTime.Now,
    Prop4 = "Hardcodedstring"}
  )
  .AsEnumerable()
  .Select(n=>new OtherEntity{
     Prop1 = n.Prop1,
     Prop2 = n.Prop2,
     Prop3 = n.Prop3,
     Prop4 = n.Prop4}
  );

//insert into database and save

If I try to create a new OtherEntity in the select then I get an EF exception.

Is this the only way to proceed? Makes the whole thing very cumbersome and seems a complete waste of keystrokes?


I suggest using Automapper to map from your entities to your domain objects instead of doing the mapping from within the linq query.


No, that's the only way. Until you run AsEnumerable, ToList, etc. the only methods you can call are methods that are mapped by Entity Framework to SQL syntax. Since the constructor of OtherEntity is not mapped to anything, this is impossible to call it within an Entity context.


my favorite solution for this is to create a Convertor class, that takes Source parameter (either list or single object) and transfer it (create new instance and assign values to it) to the destination class type

List<OtherEntity> lst = Convertor.ConvertToOtherEntity(newEntities );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜