EF4.0-有没有一种方法可以查看在调试过程中哪些实体附加到了什么ObjectContext
本文关键字:实体 过程中 调试 ObjectContext 什么 有没有 一种 方法 EF4 | 更新日期: 2023-09-27 17:58:27
这是我的问题的延续。
我正在尝试使用Julie Lerman几个月前给我的解决方案。我目前正在使用以下内容生成一个新的游戏实体,该实体预先附加到我的ObjectContext:
Game game = _gameRepository.GetGame(formData.GameID);
AutoMapper.Mapper.Map<AdminGameEditModel, Game>(formData, game);
在存储库中,我尝试将游戏附加到OC,并将其状态设置为"已添加",就像她建议的那样,方法如下:
public Game GetGame(int id)
{
if (id > 0)
{
return _siteDB.Games.Include("Genre").Include("Platforms").SingleOrDefault(g => g.GameID == id);
}
else
{
Game game = _siteDB.Games.CreateObject();
_siteDB.Games.AddObject(game);
return game;
}
}
现在,为了清楚起见,这里是我的控制器的整体构造函数:
public AdminController(IArticleRepository articleRepository, IGameRepository gameRepository, INewsRepository newsRepository)
{
_articleRepository = articleRepository;
_gameRepository = gameRepository;
_newsRepository = newsRepository;
Mapper.CreateMap<AdminGameEditModel, Game>()
.BeforeMap((s, d) =>
{
if (d.Platforms.Count > 0)
{
Platform[] existing = d.Platforms.ToArray();
foreach (var plat in existing)
{
d.Platforms.Remove(plat);
}
}
foreach (var platId in s.PlatformIDs)
{
Platform newPlat = _gameRepository.GetPlatform(platId);
d.Platforms.Add(newPlat);
}
})
.ForMember(dest => dest.BoxArtPath, opt => opt.Ignore())
.ForMember(dest => dest.IndexImagePath, opt => opt.Ignore())
.ForMember(dest => dest.Cons, opt => opt.MapFrom(src => String.Join("|", src.Cons)))
.ForMember(dest => dest.Pros, opt => opt.MapFrom(src => String.Join("|", src.Pros)))
.ForMember(dest => dest.LastModified, opt => opt.UseValue(DateTime.Now))
.ForMember(dest => dest.Platforms, opt => opt.Ignore());
}
正如您所看到的,_gameRepository应该是相同的,因为它是在控制器构造上创建的。这反过来意味着_gameRepository的OC对于游戏和平台应该是相同的。然而,在这种情况下,我仍然得到一个例外,它说:
无法定义这两个对象之间的关系,因为它们附加到不同的ObjectContext对象。
肯定发生了一些奇怪的事情,这就是为什么我想知道我是否真的可以跟踪实体实际连接到哪个ObjectContext。它们都应该连接到同一个OC,但异常声明不同。
也许这与我使用Ninject(香草版本,而不是MVC定制版本)在控制器中注入存储库有关。无论问题是什么,似乎都不太明显。如有任何帮助,我们将不胜感激。
EDIT:存储库的ObjectContext:
public class HGGameRepository : IGameRepository
{
private HGEntities _siteDB = new HGEntities();
// rest of class code
}
Ninject绑定:
private class HandiGamerServices : NinjectModule
{
public override void Load()
{
Bind<IArticleRepository>().To<HGArticleRepository>().InRequestScope();
Bind<IGameRepository>().To<HGGameRepository>().InRequestScope();
Bind<INewsRepository>().To<HGNewsRepository>().InRequestScope();
Bind<ErrorController>().ToSelf().InRequestScope();
}
}
您可以通过以下方式询问ObjectContext是否对某个对象有引用:
ObjectStateEntry ose;
bool isInContext = someContext.ObjectStateManager.TryGetObjectStateEntry(someObject, out ose);
有问题的部分是这个
public class HGGameRepository : IGameRepository
{
private HGEntities _siteDB = new HGEntities();
// rest of class code
}
我相信您的所有存储库在创建时都会创建自己的新上下文。相反,您应该使用构造函数注入
public class HGGameRepository : IGameRepository
{
private HGEntities _siteDB;
public HGGameRepository(HGEntities entities)
{
_siteDB= entities
}
}
然后在你的Ninject模块中包括这个
Bind<HGEntities>().ToSelf().InRequestScope();
这样,您的存储库将共享相同的上下文。