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?
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; }
}
Place all your code first entities in their own assembly and exclude the rule for that assembly.
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