Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do EntityFramework collection properties need a setter

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 ...

like image 704
MartinStettner Avatar asked Feb 05 '13 14:02

MartinStettner


2 Answers

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.

like image 177
Gert Arnold Avatar answered Nov 15 '22 08:11

Gert Arnold


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.

like image 37
Jonathan Allen Avatar answered Nov 15 '22 09:11

Jonathan Allen