Private backing field for entity framework lazy loading

久未见 提交于 2019-12-07 09:36:33

问题


I'm using Entity Framework 5 with lazy loading enabled. I have got the following code:

    private ICollection<Subscription> _subscriptions = new Collection<Subscription>();

    public virtual ICollection<Subscription> Subscriptions
    {
        get { return _subscriptions; }
        set { _subscriptions = value; }
    }

But does this make sense? I want to ensure that the public property Subscriptions is never null. Due to the virtual entity framework overrides the getter and setter to provide the lazy loading functionality.

Do I need this field or can I just use an auto property and I get an empty list if there is no Subscription?


回答1:


Your code will work if the object is constructed via the new keyword. Note however that many serializers function such that object constructors and field initializers do not work.

I have settled on the following pattern for that reason:

private ICollection<Subscription> _subscriptions;

public virtual ICollection<Subscription> Subscriptions
{
    get 
    {   
        if (_subscriptions == null) _subscriptions = 
            new Collection<Subscription>();

        return _subscriptions; 
    }
    set { _subscriptions = value; }
}

This code pattern works with EF, and works whether the object is instantiated with new or with a serializer that doesn't run the object's initialization code.

The get can also be more compactly written using the null-coalescing operator:

    get 
    {   
        return _subscriptions ?? (_subscriptions = 
            new Collection<Subscription>()); 
    }


来源:https://stackoverflow.com/questions/14732945/private-backing-field-for-entity-framework-lazy-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!