In Entity Framework Core (EF Core), the DbSet represents a collection of entities of a specific type that can be queried and saved. It serves as a bridge between your application and the database, allowing you to perform CRUD operations on your data. This tutorial explores how to define and use DbSet in your applications.
The DbSet class provides methods for querying and interacting with entities in the database. It acts like a collection for your entity types, similar to a list or a set.
To define a DbSet, include a property of type DbSet<TEntity> in your DbContext class, where TEntity is the type of entity it represents.
public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Customer> Customers { get; set; }
}
In this example, the Products property is a DbSet<Product>, representing a collection of Product entities in the database.
You can use LINQ queries on a DbSet to retrieve data from the database. EF Core translates these queries into SQL and executes them against the database.
using (var context = new ApplicationDbContext())
{
var expensiveProducts = context.Products
.Where(p => p.Price > 50)
.ToList();
}
This example demonstrates how to query all products with a price greater than 50.
You can use the DbSet to add, update, or remove entities. Changes are saved to the database when you call SaveChanges() on the DbContext.
using (var context = new ApplicationDbContext())
{
// Add a new product
var newProduct = new Product { Name = "New Product", Price = 99.99m };
context.Products.Add(newProduct);
// Update an existing product
var productToUpdate = context.Products.First();
productToUpdate.Price = 79.99m;
// Delete a product
var productToDelete = context.Products.First(p => p.Name == "Old Product");
context.Products.Remove(productToDelete);
// Save changes to the database
context.SaveChanges();
}
This example shows how to add a new product, update an existing one, and delete a product.
The DbSet in EF Core is a powerful abstraction for managing collections of entities, providing an interface for performing CRUD operations and querying data efficiently. By leveraging the capabilities of DbSet, you can build robust and scalable data access layers in your applications.