Lee Atkinson
Lee Atkinson

Reputation: 2181

Entity Framework Code First - is it possible to get EF to automatically initialise collections of child entities?

Suppose I have these in my model:

public class Foo {
 public virtual Guid Id {get; set; }
 public virtual ICollection<Bar> Bars { get; set; }
}
public class Bar {
 public virtual Guid Id {get; set; }
 public virtual Guid FooId {get; set; }
 public virtual Foo Foo {get; set; }
}

Is there any way to get EF to automatically create the Foo.Bars collection when creating a new Foo and adding a Bar?

var foo = dbContext.Foos.Create();
foo.Bars.Add(new Bar());

I do understand that I can initialise the collection myself (either in Foo's constructor or when I am creating it, but I wonder if there is any way to get EF to do it.

Upvotes: 1

Views: 143

Answers (1)

Eranga
Eranga

Reputation: 32447

Framework does not provide anything out of the box for this. You would have to write your own method for this.

public class FooService
{
    ......

    Public Foo Create()
    {
        var foo = dbContext.Foos.Create();
        foo.Bars.Add(new Bar());

        return foo;
    }

    .......
}

Upvotes: 1

Related Questions