Entity Framework won't detect changes of navigation properties

后端 未结 3 577
花落未央
花落未央 2020-12-16 14:42

I\'m having trouble with detecting changes of a navigation property:

My testing model looks like this:

public class Person
{
    public int Id { get;         


        
3条回答
  •  猫巷女王i
    2020-12-16 15:18

    First of all: You MUST follow @billy's advice to use Include. Your remark "p.Address IS NOT NULL!" is only true because you are watching p.Address in the debugger and thereby triggering lazy loading in the debugger, so the change of setting the address to null is detected. In release mode or when you don't inspect the properties in the debugger your code wouldn't work and no changes would be saved.

    So, the answer to your Edit 3 is: No.

    Second: var entry = ctx.Entry(p) only returns entity states and you didn't change an entity state but instead a relationship state, or more precisely you deleted a relationship. You can't inspect relationship states with the DbContext API but only with the ObjectContext API:

    Person p = ctx.People.Include(x => x.Address).First();
    p.Address = null;
    var objCtx = ((IObjectContextAdapter)ctx).ObjectContext;
    var objentr = objCtx.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);
    

    objentr will have an entry of type RelationshipEntry now:

    enter image description here

    EF will consider this relationship entry together with entity state entries when you call SaveChanges() and delete the relationship, i.e. set the Address foreign key column of the Person in the database to NULL.

    About Edit 2: Changing a foreign key property (which is a scalar property in your model) is a change of the entity itself, so the entity state will be Modified in this case.

提交回复
热议问题