Quick and easy DbContext setup in .NET
Sergei Belialov
Posted on May 21, 2023
In .NET, a DbContext is a class that allows you to interact with a database using entity classes. In this article, we'll explore how to create a DbContext in .NET with code examples.
Creating a DbContext
To create a DbContext
, we need to create a class that inherits from the DbContext
class. In this example, we'll create a ProductDbContext
class that represents a database of products:
public class ProductDbContext : DbContext
{
public ProductDbContext(DbContextOptions<ProductDbContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
}
This code creates a ProductDbContext
class that inherits from the DbContext
class. The constructor accepts an options
parameter of type DbContextOptions<ProductDbContext>
, which allows us to configure the database connection. In this example, we're passing the options to the base constructor.
The ProductDbContext
class also contains a DbSet<Product>
property that represents the entity set for products.
Register DbContext
In order to use the ProductDbContext class in your application, you need to register it with the dependency injection container. This can typically be done in your Startup class, like so:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Register the DbContext
services.AddDbContext<ProductDbContext>(options =>
options.UseSqlite("Data Source=products.db"));
// Other service registrations...
}
}
This code uses the AddDbContext
method to register the ProductDbContext
with the dependency injection container. It also configures the DbContext
to use SQLite as the database provider, the database file location as products.db
or you could use the connection string retrieved from the application configuration.
Migrating the Database
Once we’ve created and configured the DbContext
, we need to create the database schema. To do this, we'll use Entity Framework Core migrations.
First, install the Entity Framework Core tools using the following command:
dotnet tool install --global dotnet-ef
Next, add a migration using the following command:
dotnet ef migrations add InitialCreate
This command creates a new migration with the name InitialCreate
.
Finally, apply the migration to the database using the following command:
dotnet ef database update
This command applies the migration to the database and creates the schema.
Using the DbContext
Now that we’ve created and configured the DbContext
, we can use it to interact with the database.
public class ProductService
{
private readonly ProductDbContext _dbContext;
public ProductService(ProductDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<Product>> GetProductsAsync()
{
return await _dbContext.Products.ToListAsync();
}
public async Task<Product> GetProductByIdAsync(int id)
{
return await _dbContext.Products.FindAsync(id);
}
public async Task AddProductAsync(Product product)
{
await _dbContext.Products.AddAsync(product);
await _dbContext.SaveChangesAsync();
}
public async Task UpdateProductAsync(Product product)
{
_dbContext.Entry(product).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
}
public async Task DeleteProductAsync(int id)
{
var product = await _dbContext.Products.FindAsync(id);
_dbContext.Products.Remove(product);
await _dbContext.SaveChangesAsync();
}
}
In this example, we’ve defined a ProductService
class with a constructor that takes an instance of ProductDbContext
as a parameter. The ProductDbContext
instance is then stored in a private field called _dbContext
.
We’ve also defined a few methods for interacting with the products stored in the database. These methods use the _dbContext
instance to query, add, update, and delete Product
entities.
With this setup, you can easily use the ProductService
class in your controllers or other services, and the ProductDbContext
instance will be automatically injected by the dependency injection container. For example, here's how you might use the ProductService
class in a controller:
public class ProductsController : Controller
{
private readonly ProductService _productService;
public ProductsController(ProductService productService)
{
_productService = productService;
}
public async Task<IActionResult> Index()
{
var products = await _productService.GetProductsAsync();
return View(products);
}
// Other action methods...
}
Conclusion
In this article, we’ve explored how to create a DbContext
in .NET with code examples. We've also seen how to configure the DbContext
and use it to interact with a database using entity classes. By following these examples, you should be able to create your own DbContext
and interact with a database in your .NET application.
Posted on May 21, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.