The usual approach for modeling 1-n relations with EntityFramwork (Code First) is to use virtual collection properties like:
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 Remarks
collection is initially null
, I take the following approach
private ICollection<Remark> _remarks;
public virtual ICollection<Remark> {
get {
if (_remarks == null)
_remarks = new List<Remark>();
return _remark;
}
set {
_remarks = value;
}
}
in order to use the Remarks.Add
method on a newly created Project
object without the need to explicitely set the Property.
Afaik EF internally derives from my class and overwrites the virtual navigation properties to support lazy loading.
My question: Do I need to define the setter of a collection property? Does EF require it? I'd rather like to only expose the getter and let the class manage the collection internally.
Edit Accidentially I only noticed this related question just after postin mine, so maybe it's just a duplicate ...