开发者

Entity Framework - return the database value or create a new instance (nav property)

My setup is as follows: Entity Framework POCO (+ proxies & lazy loading). And a Person class with reference to Address:

public class Person
{
    private Address _address;
    /* Navigation property */
    public virtual Address Home 
    {
        get
        {
            return _address;
        }
        set
        {
            _address = value;
        }
    }
}

The problem is that this is a 0..1 property and can be null. The question is - how can I create a new instance of Address if it is null. Lazy loading does not create a new instance aumatically (and it shouldn't) and if I rewrite the getter as follows it just always creates a new Address:

    private Address _address;
    /* Navigation property */
    public virtual Address Home 
    {
        get
        {
            if(_address == null) Address = MyContext.CreateObject<Address>();
 开发者_如何学运维           return _address;
        }
        set
        {
            _address = value;
        }
    }

So if never actually goes from null to a real value like this (I am guessing that this has to do with EF lazy loading & proxy property overloading mechanism). Checking for null in the constructor also does not help - same outcome - always creates a new Address.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜