I am using the latest version of entity framework (6.1.3) and i have the following class which allows a customers name to be changed:
public class CustomerService
{
public void ChangeName()
{
using (TestModel ctx = new TestModel())
{
var customer = GetCustomer(ctx);
//set new name
customer.Name = "New Name";
SaveCustomer(ctx, customer);
}
}
private Customer GetCustomer(TestModel ctx)
{
//get customer by email
var customer = ctx.Customers
.AsNoTracking()
.Include(n => n.Country) //Load Shipping Country
.Include(n => n.Country1) //Load Billing Country
.Where(n => n.Email == "test@test.com")
.Single();
return customer;
}
private void SaveCustomer(TestModel ctx, Customer customer)
{
//save back
ctx.Customers.Attach(customer); // getting error here
ctx.Entry(customer).State = EntityState.Modified;
ctx.SaveChanges();
}
}
In the sql server database i have 2 tables:
Customer-Id,Name,ShippingCountryId(Foreign Key),BillingCountryId(Foreign Key)Country-Id,Name
When i call the ChangeName method i get the following error:
Attaching an entity of type 'TestConsoleApp.customermodel.Country' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
I have been doing some debugging and found the following:
- If i remove the
AsNoTrackingcall then there is no error - If i remove one of the Includes (keeping
AsNoTrackingin) then there is no error
So it looks like the combination of AsNoTracking and 2 Includes that are of the same type causes the issue.
Can anyone suggest why i get this error and how i would resolve it? (At the same time keeping AsNoTracking and the 2 Includes in my code).
I reuse the GetCustomer method in other places thats why i want to keep AsNoTracking and the 2 Includes in.