Home > Net >  What is the difference between context.Add() and context.Entity.add() in Entity Framework Core 7?
What is the difference between context.Add() and context.Entity.add() in Entity Framework Core 7?

Time:12-31

When I want to add a new data set to my database via Entity Framework Core I first create the entity and fill it with data and then I can either call context.Add(entityData); OR context.Entity.Add(entityData); I have seen code examples doing it both ways, the official Microsoft documentation does it the second way but I can't find anything explaining the different. Looking at the Visual Studio code hints it looks like they are the same. Is there any functional difference between the two and if so when would I use one over the other?

CodePudding user response:

DbSet.Add

Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

And DbContext.Add

Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

Do the same thing.

Actually the implementations looks the same - DbSet via InternalDbSet and DbContext via SetEntityState.

  • Related