繁体   English   中英

实体框架关系属性是否更新?

[英]Do Entity Framework Relationship Properties Update?

我在 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
    }
}

所以我不确定为什么会发生我提到的错误。 是自包含的。

如果您正在使用共享上下文(您没有为每个请求/工作单元创建ObjectContex ),那么答案是肯定的,解释在这里- ObjectContext为由主键标识的每条记录创建一个实体实例,并且该实例被重用于每个后续请求(称为身份 map 模式)。 因此,如果您共享上下文并且您拥有多线程应用程序(如 web 服务、asp.net 等)所有线程可以同时使用相同的实体实例并修改相同的相关对象集合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM