I'm using EF 6.1
I have entries, containing an user which itself contains a city. The entry also has a supplier. I retrieve my entries with .AsNoTracking():
return dbContext.Set<entry>() .Include(x => x.user.city) .Include(x => x.supplier).AsNoTracking().ToList();
I have even more properties but they are all similar.
The user sees one entry and can change all member variables of all properties. He can change the entry id (not the PrimaryKey). He can change the user's last name. He can change the city's name or zip code. And so on...
Think about this example:
entry: id = 123
user: first_name = "Foo", last_name = "Bar"
city: name = "FooCity", zip_code = "4711"
The user sees this. He can now change the first_name to "Peter" and click save. Then I'm doing this:
dbContext.Set<entry>().Add(modifiedAndNotTrackedEntry); dbContext.Entry(modifiedAndNotTrackedEntry).State = EntityState.Modified; dbContext.SaveChanges();
But then EF duplicates all child entites. So in the DB I have a new user, which might be what I want if the user does not yet exist. But this user points to a new city altough the city wasn't changed. Furthermore the supplier now exists two times in the database.
I have used
AsNoTracking() because the user sees the real entity. If he changes something it directly affects all entities: Setting first_name to "Peter" all entries which had "Foo" "Bar" as user, then have "Peter" "Bar" as user. But only the modified entity should have this change. I think that happens because I directly modify the member variable of the "real" entity in the context.
How can I reattach a modified entity without recreating existing child entities.
How can I achieve what I want without using
IÂ´m trying same thing as you, iÂ´m not sure to understand quite well your reasson thought, but probably this document will help you.
Also, iÂ´m almost sure that you donÂ´t need to execute .Add() in your example, that will result in new record most of the cases, or in "Unchanged" if apply.
I can achieve to attach same entity with new values just by attaching and applying state = modified, still researching how to re-attach related properties (my worst problem is the 1toN relationship)
Check under "Attaching an existing entity to the context", probably it leads you a solution.
IÂ´m also researching an interesting post here in code project: https://www.codeproject.com/Articles/33088/Reattaching-Entity-Graphs-with-the-Entity-Framewor
It seems this guy invented an extension to re-attach node graphs on entity framework, like "here you have the missing feature from EF." IÂ´ll give it a try.