在Linq投影中设置EntityCollection

时间:2010-12-28 14:48:08

标签: linq entity-framework linq-to-entities

我想知道如何在Linq Projection中设置EntityCollection。 以下是我的代码:

var orders = (from order in context.Orders
   select new
   {
    reference = order.reference,
    pe = order.OrderExecutions //this is an EntityCollection
   })
.AsEnumerable()
.Select(o =>
     (Orders)new Orders
     {
      reference = o.reference,
      OrderExecutions = o.pe
     }
).ToList().AsQueryable();

(这段代码看起来很奇怪,但为了在telerik网格中工作,它需要像这样)

指令OrderExecutions = o.pe涉及此错误:

  

EntityCollection已经存在   初始化。该   InitializeRelatedCollection方法   应该只调用初始化a   新的EntityCollection期间   对象图的反序列化。

OrderExecutions是对象Orders中包含的EntityCollection。

如何避免此错误?有什么想法吗?

我应该修改Order对象中生成的代码吗?

[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("PModel", "FK__orderExec__refer__70DDC3D8", "OrderExecutions")]
public EntityCollection<OrderExecutions> OrderExecutions
{
 get
 {
  return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<OrderExecutions>("PModel.FK__orderExec__refer__70DDC3D8", "OrderExecutions");
 }
 set
 {
  if ((value != null))
  {
   ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<OrderExecutions>("PModel.FK__orderExec__refer__70DDC3D8", "OrderExecutions", value);
  }
 }
}

提前谢谢。

1 个答案:

答案 0 :(得分:0)

查询应该重写为

var orders = from order in context.Orders
             select new
             {
                 reference = order.reference,
                 OrderExecutions = order.OrderExecutions //this is an EntityCollection
              };

无需转换为IEnumerable,然后重新选择相同的字段。然后没有必要转换为List,然后返回到IQueryable,因为LINQ查询自然返回一个IQueryable对象。通过调用ToList(),对数据源执行查询 。在实施任何其他限制之后,推迟这些调用几乎总是更好。