Ramifications of DbSet.Create versus new Entity()

A scenario where using DbSet<T>.Create() makes sense is attaching an existing entity to the context and then leverage lazy loading of related entities. Example:

public class Parent
{
    public int Id { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
}

The following would work then:

using (var context = new MyDbContext())
{
    var parent = context.Parents.Create();
    parent.Id = 1; // assuming it exists in the DB
    context.Parents.Attach(parent);

    foreach (var child in parent.Children)
    {
        var name = child.Name;
        // ...
    }
}

Here lazy loading of children is triggered (perhaps with resulting empty collection, but not null). If you’d replace context.Parents.Create() by new Parent() the foreach loop will crash because parent.Children is always null.

Edit

Another example was here (populating a foreign key property of a new entity and then getting the navigation property lazily loaded after the new entity is inserted into the DB): Lazy loading properties after an insert

Leave a Comment