4

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)

Omu
  • 69,856
  • 92
  • 277
  • 407

1 Answers1

5

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).

Romain
  • 12,679
  • 3
  • 41
  • 54
  • well, when I don't do inserts, the EF fills it with Bars, without my initialization – Omu Feb 22 '11 at 08:31
  • May be smart to do lazy initialization then (in the getter, if Bars is not initialized, create a new collection). – Romain Feb 22 '11 at 14:22