Which one must I use, MyDbContext.Blogs.Add(ablog) or MyDbContext.Add(ablog)?

♀尐吖头ヾ 提交于 2019-12-31 04:23:06

问题


Consider I have a context MyDbContext inherits DbContext of EFCore 2.0. Blogs is a DbSet<Blog> and Blog is an entity model.

When I add a new Blog instance, ablog to the Blogs, which one must I use?

MyDbContext.Add(ablog); or MyDbContext.Blogs.Add(ablog);?

How about Find?

MyDbContext.Find<Blog>(1); or MyDbContext.Blogs.Find(1);?

Is there any benefit to use one over the other one?


回答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).

But there is no difference because:

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.

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.



来源:https://stackoverflow.com/questions/46510059/which-one-must-i-use-mydbcontext-blogs-addablog-or-mydbcontext-addablog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!