Entity Framework will only set related entity property to “null” if I first get the property

前端 未结 6 979
难免孤独
难免孤独 2021-01-14 00:50

Edit This seems to occur for any Entity property that references another entity in one direction. In other words, for the below example, the fact

6条回答
  •  迷失自我
    2021-01-14 01:17

    A way to make it work is using the property API:

    var foo = context.Foos.Find(1);
    
    context.Entry(foo).Reference(f => f.Bar).CurrentValue = null;
    
    context.SaveChanges();
    

    The benefit is that this works without loading the foo.Bar by lazy loading and it also works for pure POCOs that don't support lazy loading or change tracking proxies (no virtual properties). The downside is that you need a context instance available at the place where you want to set the related Bar to null.

提交回复
热议问题