有必要总是选择()吗?新{立刻}. .AsEnumerable . .每次选择(new EntityType{})

本文关键字:选择 EntityType 立刻 AsEnumerable new | 更新日期: 2023-09-27 18:10:01

我一直运行到一个模式,我想从一个实体集合(EF4)中选择行,并使用数据在不同的实体集合中创建新行。

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

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异常。

这是唯一的方法吗?使整个事情变得非常麻烦,似乎完全浪费了按键?

有必要总是选择()吗?新{立刻}. .AsEnumerable . .每次选择(new EntityType{})

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

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

我最喜欢的解决方案是创建一个Convertor类,它接受Source参数(列表或单个对象)并将其(创建新实例并为其赋值)转移到destination class type

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