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

The one-many or many-many relationship in the 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 only be read."

Protecting the protected setter does not help and makes it closed: -

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>) does not seem to have open or secure callers."

I would prefer not to disable the rule all over the world, because the situation that exists to prevent is quite important, but suppressing it locally every time I want to declare a relationship, it seems that it is not. Is there a way to declare a connection that does not violate CA2227?

+5
2

.

+4

:

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

    public int Id { get; set; }
    public virtual ICollection<Bar> Bars { get; private set; }
}
+5

All Articles