Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Entity 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?

like image 519
BlueChippy Avatar asked Nov 05 '22 13:11

BlueChippy


1 Answers

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

like image 185
VdesmedT Avatar answered Nov 15 '22 05:11

VdesmedT