CRUD is an acronym that stands for Create, Read, Update, and Delete. These are the four basic operations that can be performed on data in a database. In this article, we will take a look at how to use Entity Framework Core, a popular ORM (Object-Relational Mapping) framework, to perform these operations on a database.
What is Entity Framework Core?
Entity Framework Core is a lightweight and extensible version of the popular Entity Framework data access technology. It is an open-source, cross-platform framework that allows you to easily access and manipulate data stored in a variety of databases. Entity Framework Core uses a code-first approach, which means you can create your database schema directly from your C# classes.
Creating a record
To create a new record in a database table using Entity Framework Core, you can use the Add
method of the DbSet
class. This method takes an entity object as an argument and adds it to the database context. For example, to insert a new customer into a Customers
table, you might use code like this:
Copy codeusing (var context = new AppDbContext())
{
var customer = new Customer
{
Name = \"John Smith\",
Email = \"john@example.com\"
};
context.Customers.Add(customer);
context.SaveChanges();
}
Reading a record
To read a record from a database using Entity Framework Core, you can use the Find
method of the DbSet
class. This method takes the primary key of the entity as an argument and returns the entity object if it is found in the database. For example, to retrieve a customer with a specific ID from the Customers
table, you might use code like this:
Copy codeusing (var context = new AppDbContext())
{
var customer = context.Customers.Find(1);
}
Updating a record
To update an existing record in a database table using Entity Framework Core, you can use the Update
method of the DbSet
class. This method takes an entity object as an argument and marks it as modified in the database context. For example, to update the email address of a customer in the Customers
table, you might use code like this:
Copy codeusing (var context = new AppDbContext())
{
var customer = context.Customers.Find(1);
customer.Email = \"newemail@example.com\";
context.Customers.Update(customer);
context.SaveChanges();
}
Deleting a record
To delete a record from a database table using Entity Framework Core, you can use the Remove
method of the DbSet
class. This method takes an entity object as an argument and marks it as deleted in the database context. For example, to delete a customer from the Customers
table, you might use code like this:
Copy codeusing (var context = new AppDbContext())
{
var customer = context.Customers.Find(1);
context.Customers.Remove(customer);
context.SaveChanges();
}
Conclusion
Entity Framework Core is a powerful and easy-to-use framework for accessing and manipulating data in a database. By using the Add
, Find
, Update
, and Remove
methods of the DbSet
class, you can easily perform
Leave a Reply