简体   繁体   English

如何避免在实体框架中分散多个上下文

[英]How to avoid spinning up multiple contexts in entity framework

In Entity framework, trying to run the following code: 在实体框架中,尝试运行以下代码:

        using (MyEntities ctx = new myEntities())
        {
            Entity.Customers.Build buildId = new ctx.Build();
            buildId.CustomerService = customerService;
            buildId.datCreatedDate = DateTime.Now;
            buildId.strBuildSchema = schema;
            buildId.Status = "Success";
            ctx.AddToBuilds(buildId);
            ctx.SaveChanges();
        }

Results in the error "An entity object cannot be referenced by multiple instances of IEntityChangeTracker". 导致错误“ IEntityChangeTracker的多个实例无法引用实体对象”。

As far as I can tell, the problem is that the Build object I'm creating comes from a new instance of the Entity Framework context which is distinct from the context that does the AddToBuilds() statement. 据我所知,问题在于我正在创建的Build对象来自实体框架上下文的新实例,该实例不同于执行AddToBuilds()语句的上下文。

However I can't work out how to get past this problem. 但是我无法解决该问题。 I can't seem to create a new Build direct from an instantiation of the Entity context object ie ctx in the code above? 我似乎无法从实体上下文对象的实例(即上面的代码中的ctx)直接创建新的Build? Is there a way to do this, or am I missing another obvious workaround? 有没有办法做到这一点,还是我错过了另一个明显的解决方法?

Cheers, Matt 干杯,马特

The problem is that you're associating an entity which is attached to one context, not shown in the code above ( customerService ?) with another entity, buildId , which is attached to ctx . 问题在于,您正在将一个附加到一个上下文的实体(上面的代码( customerService吗?)中未显示)与另一个附加到ctx实体buildId Don't do that. 不要那样做 Use one context at a time. 一次使用一个上下文。

"customerService" (or perhaps 'schema') belongs to another EntityTracker. “ customerService”(或“ schema”)属于另一个EntityTracker。 The simplest way to get rid of this is to add the following line of code in the code which loaded customerService (note, making an assumption about the class name of customerService here): 消除此问题的最简单方法是在加载了customerService的代码中添加以下代码行(请注意,在此处对customerService的类名进行假设):

ctx.CustomerService.MergeOptions = MergeOptions.NoTracking;

This line of code tells the context "I'm not going to be making any changes to CustomerService objects, so don't bother tracking them". 这行代码告诉上下文“我将不会对CustomerService对象进行任何更改,因此不必费心跟踪它们”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM