实体对象不能被IEntityChangeTracker的多个实例引用,即使我分离了它
本文关键字:分离 引用 实例 不能 对象 IEntityChangeTracker 实体 | 更新日期: 2023-09-27 17:58:43
我正在使用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。
我还需要做其他步骤吗?我的分离丢失了什么吗?
分离只影响传递给方法的特定对象。如果要分离的对象在对象上下文中具有相关对象,则不会分离这些对象。