2011-09-27 28 views
4

我不断遇到一种模式,我希望从实体集合(EF4)中选择行并使用这些数据在不同实体集合中创建新行。是否有必要每次都选择()... new {Anon} ... AsEnumerable ... Select(new EntityType {})?

我发现做到这一点的唯一方法是执行以下步骤:

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 

如果我尝试创建在选择一个新的OtherEntity然后我得到的EF例外。

这是继续进行的唯一方法吗?使整个事情非常繁琐,似乎完全浪费击键?

回答

0

我喜欢这个解决方案是创建一个Convertor类,这需要Source参数(无论是列表或单个对象),并将其传输(创建新实例,并赋值给它)到destination class type

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

我想我会使用某种转换器只是为了保持代码更清晰和更具可读性。 – BlueChippy

1

我建议使用Automapper从您的实体映射到您的域对象,而不是从linq查询中进行映射。

+0

这是为了从实体映射到实体而不是实体到域到实体。我使用automapper为实体viewmodel。 – BlueChippy

1

不,这是唯一的方法。 在运行AsEnumerable,ToList等之前,您可以调用的唯一方法是由Entity Framework映射到SQL语法的方法。 因为OtherEntity的构造函数没有映射到任何东西,所以在Entity上下文中调用它是不可能的。

相关问题