Private backing field for entity framework lazy lo

2019-05-06 22:00发布

问题:

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