实体框架延迟加载的专用后备字段 [英] Private backing field for entity framework lazy loading
问题描述
我正在使用启用了延迟加载的Entity Framework 5.我有以下代码:
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; }
}
但这有意义吗?我想确保公共属性Subscriptions
永远不会为空.由于虚拟实体框架覆盖了getter和setter以提供延迟加载功能.
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.
我是否需要此字段,或者是否可以仅使用auto属性,如果没有订阅,我会得到一个空列表?
Do I need this field or can I just use an auto property and I get an empty list if there is no Subscription?
推荐答案
如果对象是通过 new 关键字构造的,则您的代码将起作用.但是请注意,许多序列化程序会导致对象构造函数和字段初始化程序不起作用.
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; }
}
此代码模式适用于EF,无论对象是使用 new 实例化还是使用不运行对象初始化代码的序列化程序实例化.
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.
get 也可以使用null运算符更紧凑地编写:
The get can also be more compactly written using the null-coalescing operator:
get
{
return _subscriptions ?? (_subscriptions =
new Collection<Subscription>());
}
这篇关于实体框架延迟加载的专用后备字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!