Ramifications of DbSet.Create versus new Entity()

后端 未结 1 666
孤城傲影
孤城傲影 2020-11-30 06:18

I am a bit confused about whether to use DbSet.Create, or simply new up an entity and add it. I don\'t really understand the ramifications of using DbSet.Create.

I

相关标签:
1条回答
  • 2020-11-30 06:45

    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

    0 讨论(0)
提交回复
热议问题