Entity Framework - Updating relationship by changing foreign key

前端 未结 2 842
别那么骄傲
别那么骄傲 2021-02-06 02:32

I have the two following models and DbContext:

    public class TestDbContext : DbContext
    {
        public IDbSet People { get; set; }
              


        
2条回答
  •  既然无缘
    2021-02-06 03:23

    I believe this is a problem of independent vs foreign key association. You are using independent association at the moment and the relation between car and person is actually managed by separate entry object which has its own state (to access this object you must use ObjectContext API). Setting the car's entity entry to modified state will not change the state of the entry for the relation! The simple solution is to use foreign key association instead which means adding new Guid PersonId property to your car and map it as foreign key property for Person navigation property.

    If you insist on using independent associations you should change relations only on attached entities otherwise you will had a strong headache with tracking those changes and setting all required entries with correct state. It should be enough to create objects, attach them to context and only after that set the owner of the car - hopefully it will be tracked as a change.

提交回复
热议问题