should I initialize collections in the constructor

冷暖自知 提交于 2019-12-23 13:08:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!