Share via


DbContext Class

Definition

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification="Casing is intentional")]
public class DbContext : IDisposable, System.Data.Entity.Infrastructure.IObjectContextAdapter
public class DbContext : IDisposable, System.Data.Entity.Infrastructure.IObjectContextAdapter
type DbContext = class
    interface IDisposable
    interface IObjectContextAdapter
Public Class DbContext
Implements IDisposable, IObjectContextAdapter
Inheritance
DbContext
Derived
Attributes
Implements

Remarks

DbContext is usually used with a derived type that contains DbSet<TEntity> properties for the root entities of the model. These sets are automatically initialized when the instance of the derived class is created. This behavior can be modified by applying the SuppressDbSetInitializationAttribute attribute to either the entire derived context class, or to individual properties on the class. The Entity Data Model backing the context can be specified in several ways. When using the Code First approach, the DbSet<TEntity> properties on the derived context are used to build a model by convention. The protected OnModelCreating method can be overridden to tweak this model. More control over the model used for the Model First approach can be obtained by creating a DbCompiledModel explicitly from a DbModelBuilder and passing this model to one of the DbContext constructors. When using the Database First or Model First approach the Entity Data Model can be created using the Entity Designer (or manually through creation of an EDMX file) and then this model can be specified using entity connection string or an EntityConnection object. The connection to the database (including the name of the database) can be specified in several ways. If the parameterless DbContext constructor is called from a derived context, then the name of the derived context is used to find a connection string in the app.config or web.config file. If no connection string is found, then the name is passed to the DefaultConnectionFactory registered on the Database class. The connection factory then uses the context name as the database name in a default connection string. (This default connection string points to .\SQLEXPRESS on the local machine unless a different DefaultConnectionFactory is registered.) Instead of using the derived context name, the connection/database name can also be specified explicitly by passing the name to one of the DbContext constructors that takes a string. The name can also be passed in the form "name=myname", in which case the name must be found in the config file or an exception will be thrown. Note that the connection found in the app.config or web.config file can be a normal database connection string (not a special Entity Framework connection string) in which case the DbContext will use Code First. However, if the connection found in the config file is a special Entity Framework connection string, then the DbContext will use Database/Model First and the model specified in the connection string will be used. An existing or explicitly created DbConnection can also be used instead of the database/connection name. A DbModelBuilderVersionAttribute can be applied to a class derived from DbContext to set the version of conventions used by the context when it creates a model. If no attribute is applied then the latest version of conventions will be used.

Constructors

DbContext()

Constructs a new context instance using conventions to create the name of the database to which a connection will be made. The by-convention name is the full name (namespace + class name) of the derived context class. See the class remarks for how this is used to create a connection.

DbContext(DbCompiledModel)

Constructs a new context instance using conventions to create the name of the database to which a connection will be made, and initializes it from the given model. The by-convention name is the full name (namespace + class name) of the derived context class. See the class remarks for how this is used to create a connection.

DbContext(DbConnection, Boolean)

Constructs a new context instance using the existing connection to connect to a database. The connection will not be disposed when the context is disposed if contextOwnsConnection is false.

DbContext(DbConnection, DbCompiledModel, Boolean)

Constructs a new context instance using the existing connection to connect to a database, and initializes it from the given model. The connection will not be disposed when the context is disposed if contextOwnsConnection is false.

DbContext(ObjectContext, Boolean)

Constructs a new context instance around an existing ObjectContext.

DbContext(ObjectContext, Boolean)

Constructs a new context instance around an existing ObjectContext.

DbContext(String, DbCompiledModel)

Constructs a new context instance using the given string as the name or connection string for the database to which a connection will be made, and initializes it from the given model. See the class remarks for how this is used to create a connection.

DbContext(String)

Constructs a new context instance using the given string as the name or connection string for the database to which a connection will be made. See the class remarks for how this is used to create a connection.

Properties

ChangeTracker

Provides access to features of the context that deal with change tracking of entities.

Configuration

Provides access to configuration options for the context.

Database

Creates a Database instance for this context that allows for creation/deletion/existence checks for the underlying database.

Methods

Dispose()

Calls the protected Dispose method.

Dispose(Boolean)

Disposes the context. The underlying ObjectContext is also disposed if it was created is by this context or ownership was passed to this context when this context was created. The connection to the database (DbConnection object) is also disposed if it was created is by this context or ownership was passed to this context when this context was created.

Entry(Object)

Gets a DbEntityEntry object for the given entity providing access to information about the entity and the ability to perform actions on the entity.

Entry<TEntity>(TEntity)

Gets a DbEntityEntry<TEntity> object for the given entity providing access to information about the entity and the ability to perform actions on the entity.

Equals(Object)

Determines whether the specified object is equal to the current object.

GetHashCode()

Serves as the default hash function.

GetType()

Gets the Type of the current instance.

GetValidationErrors()

Validates tracked entities and returns a Collection of DbEntityValidationResult containing validation results.

OnModelCreating(DbModelBuilder)

This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down.

SaveChanges()

Saves all changes made in this context to the underlying database.

SaveChangesAsync()

Asynchronously saves all changes made in this context to the underlying database.

SaveChangesAsync(CancellationToken)

Asynchronously saves all changes made in this context to the underlying database.

Set(Type)

Returns a non-generic DbSet instance for access to entities of the given type in the context and the underlying store.

Set<TEntity>()

Returns a DbSet<TEntity> instance for access to entities of the given type in the context and the underlying store.

ShouldValidateEntity(DbEntityEntry)

Extension point allowing the user to override the default behavior of validating only added and modified entities.

ToString()

Returns a string that represents the current object.

ValidateEntity(DbEntityEntry, IDictionary<Object,Object>)

Extension point allowing the user to customize validation of an entity or filter out validation results. Called by GetValidationErrors().

Explicit Interface Implementations

IObjectContextAdapter.ObjectContext

Returns the Entity Framework ObjectContext that is underlying this context.

Applies to