An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext

烂漫一生 提交于 2019-12-05 09:53:21

The issue here looks like you are creating a separate context with each entity (Model has a new copy of db instantiated). So what happens is:

  1. You create the object and it has a context object in the entity to which it is attached
  2. You create a new object with it's own context class and set the properties you want to update
  3. It tries to save and throws an exception that the entity is already loaded in another context - the one in which it was created.

The first step to correcting this is to not create a new context inside the entity.

I agree to @Matthew

Also i would like to suggest that dbcontexts should be in a using block:

using(var db = new Database())
{
    // do something with db but not lazy loading
}

This is also a nice read for database contexts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!