问题
I have a many-to-many
relationship between Foo
and Bar
Here's a simplified Foo
public class Foo
{
public virtual ICollection<Bar> Bars {get;set;}
}
and I want to save a new foo with some bars attached:
var foo = new Foo();
foo.Bars.Add(bar1); //I'll get an error that if Bars is not initialized
repo.Insert(foo);
repo.SaveChanges();
should I initialize the Bars in the constructor, is this how it should be done ? (using EF4 CTP5 codefirst)
回答1:
I'd indeed initialize the collection in the constructor (if the collection is virtually always needed), or would change the getter to initialize whenever the collection is first needed (if the collection is not always needed).
来源:https://stackoverflow.com/questions/5075712/should-i-initialize-collections-in-the-constructor