DbSet.Create与新实体()的关系 [英] Ramifications of DbSet.Create versus new Entity()
问题描述
我明白,DbSet.Create会创建一个代理版本,如果适用,但我不太明白那意味着什么。我为什么要关心?在我看来,一个空的Proxied类没有比非代理类更有用,因为没有相关的实体来延迟加载。
你能告诉我差异超出明显?为什么要关心?
使用 DbSet< T> .Create() / code>有意义的是将现有实体附加到上下文,然后利用相关实体的延迟加载。示例:
public class Parent
{
public int Id {get;组; }
public virtual ICollection< Child>孩子{get;组; }
}
public class Child
{
public int Id {get;组; }
public string Name {get;组; }
}
以下内容将会起作用:
using(var context = new MyDbContext())
{
var parent = context.Parents.Create();
parent.Id = 1; //假设它存在于DB
context.Parents.Attach(parent);
foreach(parent中的var child)
{
var name = child.Name;
// ...
}
}
这里懒惰触发孩子的加载(可能是由于空的集合而不是 null
)。如果您将 context.Parents.Create()
替换为 new Parent()
,foreach循环将崩溃,因为 parent.Children
总是 null
。
编辑
另一个例子是这里(填充一个新实体的外键属性,然后在将新实体插入到该实体之后,将导航属性延迟加载DB):插入后延迟加载属性
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.
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?
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; }
}
The following would work then:
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;
// ...
}
}
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
.
Edit
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与新实体()的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!