我有点困惑是应该使用DbSet.Create 还是直接new一个实体并添加它。我不太理解使用DbSet.Create的影响。
我知道DbSet.Create将创建一个代理版本(如果适用),但我真的不明白这意味着什么。为什么我要关心?在我看来,一个空的代理类和非代理类一样无用,因为没有相关的实体需要进行延迟加载。
除了显而易见的区别外,您能告诉我更多的区别吗?还有,你为什么要关心呢?
我有点困惑是应该使用DbSet.Create 还是直接new一个实体并添加它。我不太理解使用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
)。如果您用new Parent()
替换context.Parents.Create()
,foreach循环将崩溃,因为parent.Children
始终为null
。
编辑
另一个例子在这里(填充新实体的外键属性,然后在将新实体插入到数据库后获取惰性加载的导航属性):Lazy loading properties after an insert