2011-05-02 141 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