Tuesday 1 January 2019

Entity Framework Core: DbContext

The DbContext class is an integral part of Entity Framework. An instance of DbContextrepresents a session with the database which can be used to query and save instances of your entities to a database. DbContext is a combination of the Unit Of Work and Repository patterns.
DbContext in EF Core allows us to perform following tasks:
  1. Manage database connection
  2. Configure model & relationship
  3. Querying database
  4. Saving data to the database
  5. Configure change tracking
  6. Caching
  7. Transaction management
To use DbContext in our application, we need to create the class that derives from DbContext, also known as context class. This context class typically includes DbSet<TEntity> properties for each entity in the model. Consider the following example of context class in EF Core.
public class SchoolContext : DbContext
{
    public SchoolContext()
    {
  
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
    //entities
    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }
} 
In the example above, the SchoolContext class is derived from the DbContext class and contains the DbSet<TEntity> properties of Student and Course type. It also overrides the OnConfiguring and OnModelCreating methods. We must create an instance of SchoolContext to connect to the database and save or retrieve Student or Course data.
The OnConfiguring() method allows us to select and configure the data source to be used with a context using DbContextOptionsBuilder. Learn how to configure a DbContext class at here.
The OnModelCreating() method allows us to configure the model using ModelBuilderFluent API.

DbContext Methods

MethodUsage
AddAdds a new entity to DbContext with Added state and starts tracking it. This new entity data will be inserted into the database when SaveChanges() is called.
AddAsyncAsynchronous method for adding a new entity to DbContext with Added state and starts tracking it. This new entity data will be inserted into the database when SaveChangesAsync() is called.
AddRangeAdds a collection of new entities to DbContext with Added state and starts tracking it. This new entity data will be inserted into the database when SaveChanges() is called.
AddRangeAsyncAsynchronous method for adding a collection of new entities which will be saved on SaveChangesAsync().
AttachAttaches a new or existing entity to DbContext with Unchanged state and starts tracking it.
AttachRangeAttaches a collection of new or existing entities to DbContext with Unchanged state and starts tracking it.
EntryGets an EntityEntry for the given entity. The entry provides access to change tracking information and operations for the entity.
FindFinds an entity with the given primary key values.
FindAsyncAsynchronous method for finding an entity with the given primary key values.
RemoveSets Deleted state to the specified entity which will delete the data when SaveChanges() is called.
RemoveRangeSets Deleted state to a collection of entities which will delete the data in a single DB round trip when SaveChanges() is called.
SaveChangesExecute INSERT, UPDATE or DELETE command to the database for the entities with Added, Modified or Deleted state.
SaveChangesAsyncAsynchronous method of SaveChanges()
SetCreates a DbSet<TEntity> that can be used to query and save instances of TEntity.
UpdateAttaches disconnected entity with Modified state and start tracking it. The data will be saved when SaveChagnes() is called.
UpdateRangeAttaches a collection of disconnected entities with Modified state and start tracking it. The data will be saved when SaveChagnes() is called.
OnConfiguringOverride this method to configure the database (and other options) to be used for this context. This method is called for each instance of the context that is created.
OnModelCreatingOverride this method to further configure the model that was discovered by convention from the entity types exposed in DbSet<TEntity> properties on your derived context.

DbContext Properties

MethodUsage
ChangeTrackerProvides access to information and operations for entity instances this context is tracking.
DatabaseProvides access to database related information and operations for this context.
ModelReturns the metadata about the shape of entities, the relationships between them, and how they map to the database.
Learn how to create the first simple EF Core console application in the next chapter.

No comments:

Post a Comment