我必须使用哪个MyDbContext.Blogs.Add(ablog)或MyDbContext.Add(ablog)? [英] Which one must I use, MyDbContext.Blogs.Add(ablog) or MyDbContext.Add(ablog)?

查看:137
本文介绍了我必须使用哪个MyDbContext.Blogs.Add(ablog)或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 the context begins tracking the entity that was passed in to the method and applies an EntityState value of Added to it. The context also applies the same EntityState value of Added to all other objects in the graph that aren't already being tracked by the context.

也有 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆