Eri*_*sch 52 entity-framework entity-framework-4.1
我对是否使用DbSet.Create感到有点困惑,或者只是新建一个实体并添加它.我真的不明白使用DbSet.Create的后果.
据我所知,如果适用,DbSet.Create将创建一个代理版本,但我真的不明白这意味着什么.我为什么在意?在我看来,一个空的Proxied类并不比非代理类更有用,因为没有相关的实体来延迟加载.
除了显而易见的事情,你能告诉我差异吗?你为什么要关心?
Sla*_*uma 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; }
}
Run Code Online (Sandbox Code Playgroud)
以下将适用于:
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;
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
这里触发了延迟加载的子项(可能导致空集合,但不是null).如果您想更换context.Parents.Create()由new Parent()foreach循环会崩溃,因为parent.Children始终null.
编辑
另一个例子是这里(填充新实体的外键属性,然后在将新实体插入数据库后延迟加载导航属性):插入后的延迟加载属性
| 归档时间: |
|
| 查看次数: |
7917 次 |
| 最近记录: |