Do EntityFramework collection properties need a setter
Asked Answered
C

2

5

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

Chrisom answered 5/2, 2013 at 14:54 Comment(1)
heads up for learn.microsoft.com/en-us/visualstudio/code-quality/…Acid
C
10

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.

Camise answered 5/2, 2013 at 18:21 Comment(0)
L
3

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.

Loeb answered 30/12, 2019 at 5:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.