Ramifications of DbSet.Create versus new Entity()

允我心安 提交于 2019-11-27 04:20:23
Slauma

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!