问题
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