Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First and CA2227 "Collection Properties should be read only"

A one-many or many-many relationship in Entity Framework Code First looks like this:-

public class Foo
{
  public int Id { get; set; }
  public virtual ICollection<Bar> Bars { get; set; }
}

This violates Code Analysis rule 2227 "Collection Properties should be read only".

Making the setter protected doesn't help, and making it private:-

public class Foo
{
  public int Id { get; set; }
  public virtual ICollection<Bar> Bars { get; private set; }
}

then of course violates CA1811 "Foo.Bars.set(ICollection<Bar>) appears to have no upstream public or protected callers".

I'd rather not turn the rule off globally because the situation it exists to prevent is fairly important, but suppressing it locally every time I want to declare a relationship seems off. Is there a way to declare the relationship that doesn't violate CA2227?

like image 588
Iain Galloway Avatar asked Jun 21 '12 13:06

Iain Galloway


2 Answers

Change your code to the following:

public class Foo {
    public Foo() {
        Bars = new Collection<Bar>();
    }

    public int Id { get; set; }
    public virtual ICollection<Bar> Bars { get; private set; }
}
like image 51
Professor of programming Avatar answered Oct 17 '22 21:10

Professor of programming


Place all your code first entities in their own assembly and exclude the rule for that assembly.

like image 43
Steven Avatar answered Oct 17 '22 21:10

Steven