如何从 EF Code First 上下文中分离实体
这看起来比应有的要困难得多。
我正在使用 MVC3、SQL Compact Edition 和 Entity Frameworks Code First 编写一个事件注册站点,并使用 Steven Sanderson 的 Mvc Scaffolding NuGet 包。
由于事件列表不太可能发生太大变化,因此我将其缓存到 Application_Start 方法中的全局列表中:
var repo = new RaceEventRepository();
EventRaces =
repo.All.Where(r => r.RaceName.Contains(eventName)).Select(r => r).ToList();
其中 RaceEventRepository 是由 MvcScaffolding 构造的存储库类,并执行一个操作,
EventContext context = new EventContext();
然后在整个存储库中使用它,并且(我假设)在存储库被处置时也被处置。 EventRaces 是一个全球可用的列表。
我的问题是,当我使用指向存储在 EventRaces 中的 RaceEvent 的外键创建注册者记录时,我收到错误“实体对象不能被 IEntityChangeTracker 的多个实例引用。”
根据几篇博客文章和 SO 答案,我需要从上下文中分离缓存的实体,如 本文的清单 1。
我的问题是,使用 ObjectBrowser,我找不到带有 Detach 方法的任何内容。存储库中的上下文没有。上下文中的各个 DbSet 没有(尽管它们有 Attach() 方法)。 System.Data.Object.ObjectSet 有一个,但我找不到 DbSet 和 ObjectSet 之间的映射。
显然,我错过了一些东西。有人能指出我正确的方向吗?
This seems a lot harder than it should be.
I'm writing an event registration site using MVC3, SQL Compact Edition, and Entity Frameworks Code First, and making use of Steven Sanderson's Mvc Scaffolding NuGet package.
Since the list of events isn't likely to change much, I'm caching it into a global list in the Application_Start method:
var repo = new RaceEventRepository();
EventRaces =
repo.All.Where(r => r.RaceName.Contains(eventName)).Select(r => r).ToList();
where RaceEventRepository is a repository class constructed by MvcScaffolding, and does a
EventContext context = new EventContext();
which is then used through out the repository, and (I assume) disposed of when the Repository is disposed of.
and EventRaces is a globally available List.
My problem is that when I then create a registrant record with a foreign key back to the RaceEvent that is stored in EventRaces , I'm getting an error "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."
According to several blog posts and SO answers, I need to Detach the cached entities from the context as in Listing 1 of this post.
My problem is that, using ObjectBrowser, I can't find anything with a Detach method. context in the Repository doesn't have one. The individual DbSets in the context don't have one (although they have an Attach() method). System.Data.Object.ObjectSet has one, but I can't find a mapping between a DbSet and an ObjectSet.
Clearly, I'm missing something. Can somebody point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
AsNoTracking
扩展方法来查询列表,而不将对象附加到上下文......或者您可以通过将单个实体的状态设置为
Detached 将其与上下文分离:
You can either use the
AsNoTracking
extension method to query your list without attaching the objects to the context ...... or you can detach single entities from the context by settings their state to
Detached
: