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
You are right - this happens beacause you used lazy loading in EF (virtual
property). You may remove virtual
(but this may be impossible for you). Other way you described in your question - call property, and set this to null.
Also you could read another topic about this problem on SO.
Personally, I think Nathan's answer (lazy-loading inside the property setter) is the most robust. However, it mushrooms your domain classes (10 lines per property) and makes it less readable.
As another workaround, I compiled two methods into a extension method:
public static void SetToNull<TEntity, TProperty>(this TEntity entity, Expression<Func<TEntity, TProperty>> navigationProperty, DbContext context = null)
where TEntity : class
where TProperty : class
{
var pi = GetPropertyInfo(entity, navigationProperty);
if (context != null)
{
//If DB Context is supplied, use Entry/Reference method to null out current value
context.Entry(entity).Reference(navigationProperty).CurrentValue = null;
}
else
{
//If no DB Context, then lazy load first
var prevValue = (TProperty)pi.GetValue(entity);
}
pi.SetValue(entity, null);
}
static PropertyInfo GetPropertyInfo<TSource, TProperty>( TSource source, Expression<Func<TSource, TProperty>> propertyLambda)
{
Type type = typeof(TSource);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
return propInfo;
}
This allows you to supply a DbContext if you have one, in which case it will use the most efficient method and set the CurrentValue of the Entry Reference to null.
entity.SetToNull(e => e.ReferenceProperty, dbContext);
If no DBContext is supplied, it will lazy load first.
entity.SetToNull(e => e.ReferenceProperty);
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
.
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>(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:
As a workaround, the easiest way I've found to mitigate this issue is to have the setter call the getter before setting the backing field to null, e.g.
public class Foo
{
public int? Id { get; set; }
private Bar _bar;
public virtual Bar
{
get { return _bar; }
set
{
var entityFrameworkHack = this.Bar; //ensure the proxy has loaded
_bar = value;
}
}
}
This way, the property works regardless of whether other code has actually loaded the property yet, at the cost of a potentially unneeded entity load.
If you want to avoid manipulating the EntityEntry
, you can avoid the lazy load call to the database by including the FK property in your POCO (which you can make private if you don't want users to have access) and have the Nav property setter set that FK value to null if the setter value
is null. Example:
public class InaccessibleFKDependent
{
[Key]
public int Id { get; set; }
private int? PrincipalId { get; set; }
private InaccessibleFKPrincipal _principal;
public virtual InaccessibleFKPrincipal Principal
{
get => _principal;
set
{
if( null == value )
{
PrincipalId = null;
}
_principal = value;
}
}
}
public class InaccessibleFKDependentConfiguration : IEntityTypeConfiguration<InaccessibleFKDependent>
{
public void Configure( EntityTypeBuilder<InaccessibleFKDependent> builder )
{
builder.HasOne( d => d.Principal )
.WithMany()
.HasForeignKey( "PrincipalId" );
}
}
Test:
public static void TestInaccessibleFKSetToNull( DbContextOptions options )
{
using( var dbContext = DeleteAndRecreateDatabase( options ) )
{
var p = new InaccessibleFKPrincipal();
dbContext.Add( p );
dbContext.SaveChanges();
var d = new InaccessibleFKDependent()
{
Principal = p,
};
dbContext.Add( d );
dbContext.SaveChanges();
}
using( var dbContext = new TestContext( options ) )
{
var d = dbContext.InaccessibleFKDependentEntities.Single();
d.Principal = null;
dbContext.SaveChanges();
}
using( var dbContext = new TestContext( options ) )
{
var d = dbContext.InaccessibleFKDependentEntities
.Include( dd => dd.Principal )
.Single();
System.Console.WriteLine( $"{nameof( d )}.{nameof( d.Principal )} is NULL: {null == d.Principal}" );
}
}