实体框架关系属性更新?

时间:2011-05-02 05:09:10

标签: c# .net entity-framework

我在WCF网络方法中有一些这样的代码,

    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循环中的列表进行了部分修改。

所以要解释一下,'source'是从我们的数据库加载的实体框架实体,'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 个答案:

答案 0 :(得分:1)

如果您正在使用共享上下文(您没有为每个请求/工作单元创建ObjectContex),则答案为是,the explanation is here - ObjectContext为主要标识的每条记录创建key只有一个实体实例,并且每个后续请求都会重用此实例(称为身份映射模式)。因此,如果您共享上下文并且您具有多线程应用程序(如Web服务,asp.net等),则所有线程可以同时使用相同的实体实例并修改相关对象的相同集合。