Entity Framework won't detect changes of navigation properties

后端 未结 3 578
花落未央
花落未央 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条回答
  •  一个人的身影
    2020-12-16 15:06

    You need to include the Address nav. prop. in your query, otherwise EF won't consider changes to it when you save :

    using (var ctx = new EFContext())
    {
        Person p = ctx.People.Include(x => x.Address).First();
        //p.Address IS NOT NULL!
        p.Address = null;
        var entry = ctx.Entry(p);
    }
    

    You could also use foreign keys in your model, which I like very much :

    public class Person
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public virtual Address Address { get; set; }
    
        public int? AddressId {get; set;}
    }
    

    ...

    using (var ctx = new EFContext())
    {
        Person p = ctx.People.First();
        p.AddressId = null;
        var entry = ctx.Entry(p);
    }
    

提交回复
热议问题