The DbContext
class provided by EF Core is designed to work as a Unit Of Work (https://martinfowler.com/eaaCatalog/unitOfWork.html) that stores and tracks all the objects in the model. As a Unit Of Work, DbContext
lets you add an object for tracking, and then we set the EntityState
parameter of the object so that DbContext
can perform the correct database operation (INSERT
, UPDATE
, or DELETE
) when needed—that is, when calling the Save()
or SaveAsync()
methods.
When defining your instance of DbContext
, you added properties of the DbContext
type for each entity you wanted your model to include. The DbContext
is a special type of collection that is aware of the EntityState
objects, and lets you control them with simple methods such asAdd()
orRemove()
.
Note
EF Core scans the graph objects that are being pointed to by the object you add to it and automatically adds the referenced objects if needed.
Here is an example of how products are added in the GiveNTake
application:
//ProductsController...