25 May 2017
Entity Framework Core (EF Core) is an object-relational mapper (ORM) that allows you to interact with a database in .NET Core using object-oriented programming techniques. EF Core enables you to work with a variety of database systems in a simple and efficient way by abstracting the underlying database interactions. In this post, we will go through the basics of setting up EF Core in your .NET Core application and performing basic CRUD operations (Create, Read, Update, Delete).
1. Setting Up Entity Framework Core
Before you can start using EF Core, you need to install the necessary NuGet packages in your project. These packages allow you to communicate with a database in a manner that leverages EF Core’s features.
To get started, run the following command in your project directory to install the EF Core package:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
This will install the EF Core package for SQL Server. If you’re using another database, such as MySQL or PostgreSQL, you can install the corresponding provider.
Next, you need to create a DbContext class, which serves as the main class for interacting with your database. The DbContext
class will include DbSet properties that represent your database tables.
Here’s an example of a simple DbContext
:
public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) { }
}
In this example, the Products
property represents the Products
table in the database.
To configure your DbContext in Startup.cs, you need to add it to the dependency injection container:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Here, we’re telling EF Core to use SQL Server and to fetch the connection string from the app’s configuration.
2. Creating the Database
Once your DbContext is configured, you can create the database using EF Core migrations. Migrations allow you to apply changes to the database schema over time, such as creating tables or modifying existing ones.
To create your first migration, run the following command:
dotnet ef migrations add InitialCreate
This will generate a migration file that defines the changes to the database. Once the migration is created, you can apply it to the database with:
dotnet ef database update
After running this command, the database will be created, including the Products
table.
3. CRUD Operations Using EF Core
Now that your database is set up, let’s look at how to perform basic CRUD operations using EF Core.
a) Create Operation (Insert)
To insert a new record into the database, create an instance of your model (e.g., Product
) and add it to the DbSet. Then, save the changes to the database.
public class ProductController : Controller
{
private readonly ApplicationDbContext _context;
public ProductController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Create()
{
var newProduct = new Product { Name = "New Product", Price = 100 };
_context.Products.Add(newProduct);
_context.SaveChanges(); // Save to the database
return RedirectToAction("Index");
}
}
b) Read Operation (Select)
To read data from the database, use the DbSet
and query it. You can use methods like ToList()
, FirstOrDefault()
, or Find()
to retrieve data.
public IActionResult Index()
{
var products = _context.Products.ToList(); // Fetch all products
return View(products);
}
public IActionResult Details(int id)
{
var product = _context.Products.FirstOrDefault(p => p.Id == id);
return product == null ? NotFound() : View(product);
}
c) Update Operation
To update a record, retrieve the record, modify its properties, and then save the changes.
public IActionResult Edit(int id)
{
var product = _context.Products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
product.Name = "Updated Product Name";
product.Price = 150;
_context.SaveChanges(); // Save the updates to the database
return RedirectToAction("Index");
}
d) Delete Operation
To delete a record, retrieve the record from the database and remove it from the DbSet
.
public IActionResult Delete(int id)
{
var product = _context.Products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
_context.Products.Remove(product);
_context.SaveChanges(); // Delete from the database
return RedirectToAction("Index");
}
4. Conclusion
In this post, we’ve covered the basics of setting up and using Entity Framework Core for data access in .NET Core. We learned how to:
- Set up EF Core and configure it for SQL Server.
- Create a simple DbContext and define a DbSet for our model.
- Perform CRUD operations: Create, Read, Update, and Delete data using EF Core.
EF Core is a powerful tool that simplifies database operations and allows you to interact with your data as objects, eliminating the need to write raw SQL queries for most use cases. It supports a variety of databases and provides a flexible way to interact with your application’s data.
By mastering EF Core, you can focus more on building features for your application and less on writing low-level database interaction code.
Happy coding!