Should I always select () ... new {Anon} ... AsEnumerable ... Select (new EntityType {}) every time?

I continue to work with a template in which I want to select rows from an entity collection (EF4) and use the data to create new rows in another entity collection.

The only way I found this is to follow these steps:

var newEntities = (from e in myentities where ex == 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 option in select, I get an EF exception.

Is this the only way? Does all this make it very cumbersome and seem like a complete loss of keystrokes?

+4
source share
3 answers

My favorite solution for this is to create a Convertor class that takes a Source parameter (list or individual object) and transfers it (creates a new instance and assigns values ​​to it) to destination class type

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

I suggest using Automapper to map with your objects to your domain objects instead of doing a mapping from a linq query.

+1
source

No, this is the only way. Until you run AsEnumerable, ToList, etc., the only methods you can name are methods that map to the syntax of the Entity Framework for SQL. Since the OtherEntity constructor does not map to anything, this cannot be called in the context of Entity.

+1
source

All Articles