问题
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
Addthecontextbegins tracking the entity that was passed in to the method and applies anEntityStatevalue of Added to it. The context also applies the sameEntityStatevalue of Added to all other objects in the graph that aren't already being tracked by thecontext.
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