0

If I have an entity with a collection property for another entity. What is the best way to add a new entity and it's related entities? The problem I have is that the collection is initially null.

            var form = new Form()
            {
                Name = "TestForm"
            };
            ctx.Forms.Add(form);

            var formField = new FormField()
            {
                Name = "TestField"
            };
            form.FormFields.Add(formField);

            ctx.SaveChanges();

The form.FormFields property above is null so I get an exception. I know I could set the relationship in the other direction but I haven't defined a Form property on FormFields (and I don't really want to).

So what is the cleanest solution to for this?

  • I should have mentioned that the FormFields property is declared like this: public virtual IList FormFields { get; set; } – JasonBSteele Mar 24 '11 at 15:04

1 Answers1

0

The simplest solution is to initialize the collection like this:

var form = new Form() {
  Name = "TestForm"
  };
ctx.Forms.Add(form);
var formField = new FormField() {
  Name = "TestField"
};
if(form.FormFields == null)
  form.FormFields = new List<FormField>();
form.FormFields.Add(formField);
ctx.SaveChanges();
Devart
  • 119,203
  • 23
  • 166
  • 186