EntityFramework collection properties need an installer
A common approach for modeling 1-n relationships with EntityFramwork (Code First) is to use virtual collection properties such as:
class Project {
public virtual ICollection<Remark> Remarks { get; set; }
}
class Remark {
public virtual int ProjectId { get; set; }
public virtual Project Project {get; set; }
}
Since the collection is Remarks
native null
, I use the following approach
private ICollection<Remark> _remarks;
public virtual ICollection<Remark> {
get {
if (_remarks == null)
_remarks = new List<Remark>();
return _remark;
}
set {
_remarks = value;
}
}
to use the method Remarks.Add
on the newly created object Project
without having to explicitly set the Property.
Afaik EF internally derives from my class and overwrites the virtual navigation properties to support lazy loading.
My question is, should I define a collector for a collection property? Is EF required? I'd rather just expose the getter and let the class manage the collection internally.
Edit By chance, I only noticed this question right after the post-mine mine, so maybe it's just a duplicate ...
source to share
The Entity framework can handle private members. You can specify a private setter property:
private ICollection<Remark> _remarks;
public virtual ICollection<Remark> Remarks
{
get { return _remarks ?? (_remarks = new HashSet<Remark>()); }
private set { _remarks = value; }
}
You can even omit the setter altogether.
source to share