DEV Community

Sergei Belialov
Sergei Belialov

Posted on

Quick and easy DbContext setup in .NET

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; }
}
Enter fullscreen mode Exit fullscreen mode

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...
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Next, add a migration using the following command:

dotnet ef migrations add InitialCreate
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

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...
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)