简体   繁体   中英

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".

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.

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? 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 . Don't do that. Use one context at a time.

"customerService" (or perhaps 'schema') belongs to another 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):

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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