本文介绍了我应该在构造函数中初始化集合吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Foo
和 Bar之间有
多对多
关系
I have a many-to-many
relationship between Foo
and Bar
这里是简化的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();
我应该在构造函数中初始化Bars,这应该怎么做?
(首先使用EF4 CTP5代码)
should I initialize the Bars in the constructor, is this how it should be done ?(using EF4 CTP5 codefirst)
推荐答案
我确实会在构造函数中初始化集合(如果集合是几乎总是需要),或者会在每次需要该集合时(如果并非总是需要该集合)将getter更改为初始化。
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).
这篇关于我应该在构造函数中初始化集合吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!