开发者

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

开发者 https://www.devze.com 2023-04-07 16:12 出处:网络
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.

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

精彩评论

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

关注公众号