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 ...
Entity framework can handle private members. You can give the property a private setter:
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.
From what I've seen, EF Core doesn't need a setter either.
You do need virtual
if you are using lazy-loading. Otherwise you can omit that as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With