IEntityChangeTracker的多个实例无法引用实体对象,即使我将其分离也是如此

时间:2013-02-10 08:09:47

标签: c# asp.net asp.net-mvc entity-framework caching

我正在使用EF。我将实体保存到缓存中。

我在放入缓存之前分离每个实体,

并从缓存中获取后将其附加到新的objectContext。

我在高点使用using语句(在我的BL课程中,每次请求时)

然而我收到了这个错误:

System.InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
at System.Data.Objects.ObjectContext.VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity)
at System.Data.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet, String argumentName)
at System.Data.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Attach(Object entity)
at System.Data.Entity.DbSet`1.Attach(TEntity entity)
at Conduit.Mam.ClientService.DAL.MamData.MamDataRepository.GetMamData(String stamp, MaMDBEntities maMDBEntities) in d:\Builds\TFS\9\221\Sources\Server\ClientServices\Dev\ClientService 1.3\ServiceDAL\MamData\MamDataRepository.cs:line 56
at Conduit.Mam.ClientService.BLL.MamDataManager.GetMamData() in d:\Builds\TFS\9\221\Sources\Server\ClientServices\Dev\ClientService 1.3\Conduit.Mam.ClientService.BLL\MamDataManager.cs:line 57
at Conduit.Mam.ClientService.BLL.AppsDataManager.GetClientRelevantsApps(List`1 appsData) in d:\Builds\TFS\9\221\Sources\Server\ClientServices\Dev\ClientService 1.3\Conduit.Mam.ClientService.BLL\AppsDataManager.cs:line 107
at Conduit.Mam.ClientService.Service.Controllers.ClientDataController.GetAppsData() in d:\Builds\TFS\9\221\Sources\Server\ClientServices\Dev\ClientService 1.3\Conduit.Mam.ClientService.Service\Controllers\ClientDataController.cs:line 58   

这是我的分离+附加代码: using将objectContext注入到此处:

public static Group GetMamData(string stamp, MaMDBEntities maMDBEntities)
    {
        Group group = MamDataCacheManager.GetMamData(stamp);

        if (group == null)
        {
            //was not found in the cache
            //check for aveilable test with status 'start' - 1
            group = GetGroupsFromDb(stamp, maMDBEntities);

            if (group != null)
            {
                maMDBEntities.Entry(group).State = EntityState.Detached;

                MamDataCacheManager.InsertMamData(stamp, group);

            }
        }

        //option B: attache a new context
        if (maMDBEntities.Entry(group).State == EntityState.Detached)
        {
            maMDBEntities.Groups.Attach(group);
        }

        return group;
    }

第一次(从DB获取新实体到缓存):

该实体已分离并附加到同一contextObjec。

第二次(从缓存中获取实体),

它只附加到一个新的contextObject。

我还需要做任何额外的步骤吗?我的分离遗失了什么吗?

1 个答案:

答案 0 :(得分:1)

分离仅影响传递给方法的特定对象。如果正在分离的对象在对象上下文中具有相关对象,则不会分离这些对象。