DbSet.Create 与 new Entity() 的后果 [英] Ramifications of DbSet.Create versus new Entity()

查看:20
本文介绍了DbSet.Create 与 new Entity() 的后果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对是使用 DbSet.Create 还是简单地新建一个实体并添加它感到有些困惑.我不太明白使用 DbSet.Create 的后果.

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.

我知道 DbSet.Create 将创建一个代理版本(如果适用),但我真的不明白这意味着什么.我为什么在乎?在我看来,空的代理类并不比非代理类更有用,因为没有可延迟加载的相关实体.

I understand that DbSet.Create will create a proxied version if applicable, but I don't really understand what that means. Why do I care? It seems to me that an empty Proxied class is no more useful than a non-proxied class, since there are no related entities to lazy load.

你能告诉我有什么不同吗?你为什么要关心?

Can you tell me the difference, beyond the obvious? And why would you care?

推荐答案

使用 DbSet.Create() 有意义的场景是将现有实体附加到上下文,然后利用惰性加载相关实体.示例:

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; }
}

以下将起作用:

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).如果您将 context.Parents.Create() 替换为 new Parent() foreach 循环将崩溃,因为 parent.Children 总是 <代码>空.

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.

编辑

这里有另一个例子(填充新实体的外键属性,然后在新实体插入数据库后延迟加载导航属性):插入后延迟加载属性

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

这篇关于DbSet.Create 与 new Entity() 的后果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆