C# Entity Framework using only one ObjectContext per HttpContext

后端 未结 1 423
故里飘歌
故里飘歌 2021-01-03 04:19

In ASP.NET MVC 2, using Entity Framework 4, I\'m getting this error \"An entity object cannot be referenced by multiple instances of IEntityChangeTracker\".

A searc

相关标签:
1条回答
  • 2021-01-03 04:47

    My guess is that you've stored an object somewhere in memory (most likely the http cache using in-process mode, but could also be any manual cache such as a shared dictionary), and now you've somehow associated that object with something else, for example:

    newOrder.OwnerUser = currentUser; // <== let's say currentUser came from cache
                                      // and newOrder was on your new entity context
    

    Hence, a problem if the cached object still thinks it is attached to a context; not least, you are probably keeping an entire graph alive accidentally.


    The code looks OK (as long as you are disposing it at the end of the request), but this would be a good time to add:

    private const string EFContextKey = "EF.ObjectContext";
    

    and use that in place of the 5 literals. Avoids a few risks ;p

    0 讨论(0)
提交回复
热议问题