我对是否使用 DbSet.Create 还是简单地新建一个实体并添加它有点困惑。我真的不明白使用 DbSet.Create 的后果。
我知道 DbSet.Create 将创建一个代理版本(如果适用),但我不太明白这意味着什么。我为什么关心?在我看来,空的代理类并不比非代理类更有用,因为没有与延迟加载相关的实体。
你能告诉我除了明显的区别之外的区别吗?你为什么要关心?
使用的场景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
)。如果你想替换context.Parents.Create()
by new Parent()
foreach 循环会崩溃,因为parent.Children
总是null
.
Edit
另一个例子是这里(填充新实体的外键属性,然后在新实体插入数据库后延迟加载导航属性):插入后延迟加载属性 https://stackoverflow.com/q/6312981/270591
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)