2011-05-02 145 views
1

我有一个WCF Web方法在生产中发生错误,像这样的代码,实体框架关系属性更新?

List<LocationInRoad> locationInRoad = new List<LocationInRoad>(); 

    foreach (CarWorkLocationLink locationLink in source.CarWorkLocationLinks) 
    { 
     locationInRoad.Add(LocationInRoadMapper.MapTo(locationLink.CarWorkLocationType.WorkLocationTypeID)); 
    } 

    destination.LocationInRoad = locationInRoad.ToArray(); 

有时(也许每周一次),

InvalidOperationException has occured Message: Collection was modified; enumeration operation may not execute. 

因此,似乎在告诉我, 'source.CarWorkLocationLinks'集合已通过在foreach循环中枚举列表的方式进行了部分修改。

这样解释,“源”是从我们的数据库和“CarWorkLocationLinks”装上像这样的实体定义的实体框架的实体,

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

即它是与另一个表的实体关系。所以我想问题是,如果数据库中的某些内容发生更改,可以在加载“EntityCollection”后对其进行修改?

所以基本上整个上面的代码嵌入到WCF调用这个样子,

public APIEntity WCFCall(parameters) 
{ 
    using (EntityContext context = new EntityContext()) 
    { 
     // loading entity (database entity that is) 
     // creating API entity (this is a POCO object to control what is exposed over the WCF service) 
     // running the loop as shown above on the 'loaded entity' and popluating fields in the poco object 
     // returning the poco object 
    } 
} 

所以我不知道为什么我提到的错误应该发生。是自足的。

回答

1

如果您使用的共享上下文(没有创建ObjectContex每个请求的工作/单位),那么答案是肯定的,the explanation is here - ObjectContext创建的主键只有一个实体实例标识的每个记录,这种情况下被用于重复使用每个后续请求(它被称为标识映射模式)。因此,如果您共享上下文并且拥有多线程应用程序(如Web服务,asp.net等),则所有线程都可以同时使用相同的实体实例并修改相关对象的相同集合。

+0

好的,谢谢,真的让我思考。但我不确定这个解释100%。我会更新我的问题,因为我没有根据你的意思解释完整的上下文。 – peter 2011-05-02 21:01:36

+0

这使用每个调用的上下文,所以如果你没有在代码中执行任何嵌套线程,就不应该有任何干扰。我可以想象的唯一的另一件事是围绕懒加载和修复实体图的一些奇怪行为。 – 2011-05-02 21:18:17