我正在使用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;
}
第一次(从数据库中获取新实体到缓存中):
实体被分离并附加到相同的 contextObjec。
第二次(从缓存中获取实体),
它只附加到一个新的 contextObject。
我需要做任何额外的步骤吗?我的分离缺少什么吗?