Artificial Stupidity Artificial Stupidity - 3 years ago 202
C# Question

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download