简体   繁体   中英

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

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 that Bar overrides Equality appears to be irrelevant.

Suppose I have the following classes:

public class Foo
{
    public int? Id { get; set; }

    public virtual Bar { get; set; }

}

public class Bar : IEquatable<Bar>
{
    public int Id { get; set; }

    public override bool Equals(object obj)
    {
        var other = obj as Bar;

        return Equals(other);
    }

    public bool Equals(Bar other)
    {
        if (object.Equals(other, null))
            return false;

        return this.Id == other.Id;
    }

    public static bool operator ==(Bar left, Bar right)
    {
        return object.Equals(left, right);
    }

    public static bool operator !=(Bar left, Bar right)
    {
        return !object.Equals(left, right);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

Note that here, "Bar" intentionally has "Id" equality, because it more or less represents a lookup table - so any two object references with the same Id should always be considered the same.

Here's the weird part, this all works fine when I set Foo.Bar to another Bar instance - everything updates as expected.

However, if foo has an existing Bar when it is retrieved from the DbContext and I do:

foo.Bar = null

then the property doesn't actually change!

If I do:

var throwAway = foo.Bar;
foo.Bar = null;

Then the property will actually set and save as null.

Since the Foo.Bar property is simply a virtual, auto-implemented property, I can only conclude that this has something to do with lazy-loading and Entity Framework proxies - but why this particular scenario causes a problem, I have no idea.

Why does Entity Framework behave this way, and how can I get it to actually set null reliably?

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, eg

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.

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 .

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.

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 :

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);

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}" );
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM