c# - Entity Framework - Updating relationship by changing foreign key -
i have 2 following models , dbcontext:
public class testdbcontext : dbcontext { public idbset<person> people { get; set; } public idbset<car> cars { get; set; } } public class person { public person() { id = guid.newguid(); } public guid id { get; set; } public string name { get; set; } public virtual list<car> cars { get; set; } } public class car { public car() { id = guid.newguid(); } public guid id { get; set; } public string name { get; set; } public virtual person owner { get; set; } }
i declare list of people , list of cars, setting owner of first car first person in list:
list<person> people = new list<person>() { new person() {name = "bill", id = new guid("6f39cc2b-1a09-4e27-b803-1304afdb23e3")}, new person() {name = "ben", id = new guid("3eae0303-39d9-4fd9-af39-ec6dc73f630b")} }; list<car> cars = new list<car>() { new car() { name = "ford", owner = people[0], id = new guid("625fab6b-1d56-4f57-8c98-f9346f1bbbe4") } };
i save off database using following code , works fine.
using (testdbcontext context = new testdbcontext()) { foreach (person person in people) { if (!(context.people.any(p => p.id == person.id))) context.people.add(person); else { context.people.attach(person); context.entry<person>(person).state = system.data.entitystate.modified; } } foreach (car caar in cars) { if (!(context.cars.any(c => c.id == caar.id))) context.cars.add(caar); else { context.cars.attach(caar); context.entry<car>(caar).state = system.data.entitystate.modified; } } context.savechanges(); }
if change owner of car second person , run code again, car owner property doesn't updated.
cars[0].owner = people[1];
any ideas i'm doing wrong? help.
i believe problem of independent vs foreign key association. using independent association @ moment , relation between car , person managed separate entry object has own state (to access object must use objectcontext api). setting car's entity entry modified state not change state of entry relation! simple solution use foreign key association instead means adding new guid personid
property car , map foreign key property person
navigation property.
if insist on using independent associations should change relations on attached entities otherwise had strong headache tracking changes , setting required entries correct state. should enough create objects, attach them context , after set owner of car - tracked change.
Comments
Post a Comment