我必须使用哪个MyDbContext.Blogs.Add(ablog)或MyDbContext.Add(ablog)? [英] Which one must I use, MyDbContext.Blogs.Add(ablog) or MyDbContext.Add(ablog)?
问题描述
考虑到我有一个上下文 MyDbContext
继承了EFCore 2.0的 DbContext
。
博客
是 DbSet< Blog>
和 Blog
是实体模型。
Consider I have a context MyDbContext
inherits DbContext
of EFCore 2.0.
Blogs
is a DbSet<Blog>
and Blog
is an entity model.
当我添加新的 Blog
实例时, ablog
到博客
,我必须使用哪个?
When I add a new Blog
instance, ablog
to the Blogs
, which one must I use?
MyDbContext.Add(ablog);
或 MyDbContext.Blogs.Add(ablog);
?
查找
如何?
MyDbContext.Find< Blog>(1);
或 MyDbContext.Blogs.Find (1);
?
使用一个优于另一个是否有好处?
Is there any benefit to use one over the other one?
推荐答案
通过 DbContext
直接添加数据是 DbContext
在Entity Framework Core中,并且在 DbContext
可用的早期版本的Entity Framework中没有等效项(即从EF 4.1开始)。
Adding directly data via the DbContext
is new to the DbContext
in Entity Framework Core and have no equivalents in previous version of Entity Framework where the DbContext
is available (i.e. EF 4.1 onwards).
但是没有区别因为:
使用任何版本的
添加
上下文
开始跟踪传入方法中的
实体,并向其中应用EntityState
值。上下文还将相同的EntityState
值应用到图中的所有其他对象,这些对象尚未由<$ c跟踪
$ c>上下文。
When you use either version of
Add
thecontext
begins tracking the entity that was passed in to the method and applies anEntityState
value of Added to it. The context also applies the sameEntityState
value of Added to all other objects in the graph that aren't already being tracked by thecontext
.
也有 Add
( Add< TEntity>(TEntity实体)
),但正如Visual Studio所建议的那样,您可以省略type参数,因为编译器将从传递给方法的参数中推断类型。
Also there is a generic version of Add
(Add<TEntity>(TEntity entity)
) but as Visual Studio also suggests you can omit the type parameter because the compiler will infer the type from the argument passed in to the method.
这篇关于我必须使用哪个MyDbContext.Blogs.Add(ablog)或MyDbContext.Add(ablog)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!