DbSet.Create与new Entity()的影响

53

我有点困惑是应该使用DbSet.Create 还是直接new一个实体并添加它。我不太理解使用DbSet.Create的影响。

我知道DbSet.Create将创建一个代理版本(如果适用),但我真的不明白这意味着什么。为什么我要关心?在我看来,一个空的代理类和非代理类一样无用,因为没有相关的实体需要进行延迟加载。

除了显而易见的区别外,您能告诉我更多的区别吗?还有,你为什么要关心呢?

1个回答

55

使用DbSet<T>.Create()的情况是将现有实体附加到上下文并利用相关实体的延迟加载的场景。例如:

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; }
}
以下方法将有效:
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;
        // ...
    }
}

在这里,触发了子项的惰性加载(可能会导致空集合,但不是null)。如果您用new Parent()替换context.Parents.Create(),foreach循环将崩溃,因为parent.Children始终为null

编辑

另一个例子在这里(填充新实体的外键属性,然后在将新实体插入到数据库后获取惰性加载的导航属性):Lazy loading properties after an insert


3
啊..我没有意识到你可以仅仅填充一个外键ID,然后让它懒加载而不需要太多麻烦。我想我能理解如果你不想加载现有记录只是想要子记录的话,这可能会很有用。 - Erik Funkenbusch
如果"context.Parents"为空怎么办?我正在尝试您的案例,看起来可行,但不幸的是对于我来说"context.Parents"为空,因此会生成异常,如下所示:An exception of type 'System.NullReferenceException' occurred in YourProject.dll but was not handled in user codeAdditional information: Object reference not set to an instance of an object.如果您有任何解决方案,请告诉我,这样我就可以克服它,并在我的笔记中写下避免下次发生的方法。 - Ashish-BeJovial

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接