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

c# entity-framework entity-framework-6

Question

Edit This appears to be the case for any Entity property that makes a direct connection to another entity. To put it another way, in the example below, the information thatBar overrides It seems like equality is unimportant.

Let's say I have the upcoming 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();
    }
}

Because "Bar" essentially serves as a lookup table, it has "Id" equality in this instance; hence, any two object references with the same Id should always be regarded as being the same.

The odd thing is that everything functions as intended when I setFoo.Bar the otherBar example, everything updates as anticipated.

Although, iffoo has a currentBar after it is taken out of theDbContext and I also

foo.Bar = null

then there is no actual change to the property!

If I do:

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

The property will then be set to null and saved.

because theFoo.Bar property is just a virtual, auto-implemented property, therefore I can only guess that lazy loading and Entity Framework proxies are involved. However, I'm not sure why this particular situation poses a problem.

How does Entity Framework operate, and why doesn't it actually set the values I want it to?null reliably?

1
4
2/11/2014 8:43:45 AM

Popular Answer

ZZZ_tmp
2
2/13/2014 7:35:17 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow