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
I am not happy with the official workaround:
context.Entry(foo).Reference(f => f.Bar).CurrentValue = null;
because it involves too much contextual knowledge by the user of the POCO object. My fix is to trigger a load of the lazy property when setting the value to null so that we do not get a false positive comparison from EF:
public virtual User CheckoutUser
{
get { return checkoutUser; }
set
{
if (value != null || !LazyPropertyIsNull(CheckoutUser))
{
checkoutUser = value;
}
}
}
and in my base DbEntity class:
protected bool LazyPropertyIsNull(T currentValue) where T : DbEntity
{
return (currentValue == null);
}
Passing the property to the LazyPropertyIsNull function triggers the lazy load and the correct comparison occurs.
Please vote for this issue on the EF issues log: