How can my DbContext contain the same entity twice?

允我心安 提交于 2019-12-08 07:40:58

问题


I had to do some gymnastics to update an entity that contained a reference to another entity and I do not understand why, because in my side test project it works without.

The problem seems to be that the DbContext contains multiple entities with the same primary key but with other property changed.

So, I have to do something like the code below to set the reference correctly.

If I do not do this, I create a new "Tax" entity in the database, which is not what I want but a reference to the existing one.

 if (!Database.Set<Tax>().Local.Any(e => e.ID == invoiceDetail.Tax.ID))
    Database.Taxes.Attach(invoiceDetail.Tax);
 else
    invoiceDetail.Tax = Database.Set<Tax>().Local.Single(e => e.ID == invoiceDetail.Tax.ID);

Why do I have to check manually the Local object to make it works? Why does the DbContext contain more than 1 instance of an Entity which has the primary key identical? I am using EF4.3 in Code First (Poco).

来源:https://stackoverflow.com/questions/10179754/how-can-my-dbcontext-contain-the-same-entity-twice

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