C# 是否需要始终选择()。。。新的{Anon}。。。是否每次都选择(新EntityType{})?

C# 是否需要始终选择()。。。新的{Anon}。。。是否每次都选择(新EntityType{})?,c#,linq,entity-framework-4,C#,Linq,Entity Framework 4,我一直在运行一种模式,希望从实体集合(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"} ) .

我一直在运行一种模式,希望从实体集合(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
如果我尝试在select中创建一个新的OtherEntity,那么我会得到一个EF异常


这是唯一的办法吗?使整个过程变得非常繁琐,似乎完全是在浪费击键?

我最喜欢的解决方案是创建一个
转换器
类,该类接受
参数(列表或单个对象)并将其传输(创建新实例并为其赋值)到
目标类类型

List<OtherEntity> lst = Convertor.ConvertToOtherEntity(newEntities );
List lst=Convertor.converttoherentity(新实体);

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

不,这是唯一的方法。 在运行AsEnumerable、ToList等之前,您只能调用实体框架映射到SQL语法的方法。
由于OtherEntity的构造函数没有映射到任何对象,因此无法在实体上下文中调用它。

这是用于从实体到实体的映射,而不是从实体到域到实体的映射。我使用automapper实现实体到视图模型的转换。我想我会使用某种转换器来保持代码更清晰,可读性更强。