Entity Framework 5 does not clear navigation property

大城市里の小女人 提交于 2019-12-04 04:30:27

After the query statement (db.Vehicles.Single ...) the property is null, because you don't load it. Assigning another value to it doesn't trigger a lazy load, so nothing changes here.

Only when the property is actually loaded an assignment (any assignment, also replacing it by another object) will have an effect. If the property isn't loaded, the change tracker has nothing to track.

The property can get loaded by including it in the query

db.Vehicles.Include(v => v.ParkingBay)...

or by addressing it later in the code, e.g.

var pb = vehicle.ParkingBay; // triggers lazy loading.

or by inspecting it in the debugger (watch or quickview), which also trigger lazy loading.

Include is the recommended approach if you intend to apply any changes to navigation properties themselves.

As commented below, a better performing way to clear a reference navigation property is to expose the primitive foreign key value in the model and set it to null. In your case, this would be something like int? ParkingBayId. This pattern is know as foreign key associations, as opposed to independent associations, when only the reference property is present.

You actually need to load Property before setting it to null. I agree with Gert Arnold's answer, just wanted to add more alternatives to do it:

db.Entry(vehicle).Reference(c => c.ParkingBay).Load();
vehicle.ParkingBay = null;

OR

db.Entry(vehicle).Reference(v => v.ParkingBay).CurrentValue = null;

MSDN Relationships and Navigation Properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!