How to Use Entity Framework in Csharp

Entity Framework (EF) is a popular Object-Relational Mapping (ORM) framework for working with databases in C#. It simplifies database interactions by allowing you to work with C# objects instead of writing raw SQL queries. If you're a developer looking to streamline your coding process, mastering Entity Framework is essential.


How It Works

At its core, Entity Framework bridges the gap between your application and its database. The main idea is to use C# classes to represent database tables, enabling you to perform CRUD (Create, Read, Update, Delete) operations directly through code.

Unlike traditional approaches using ADO.NET, EF abstracts the complexity of SQL queries. Instead of manually writing queries, you interact with the database using LINQ (Language-Integrated Query). This not only saves time but also makes your code cleaner and easier to maintain.

Here's how EF is different from other techniques:

  1. Object-Relational Mapping: EF maps database schema to C# objects automatically.
  2. Code First vs. Database First: You can either create your database from code or generate code from a pre-existing database.
  3. Built-in Validation: EF can handle data validation using annotations in your model classes.

Still wondering if you should use EF? Learn more about its advantages by exploring this guide on C# access modifiers.


Code Examples

Let's explore how to use EF with practical examples. If you're new to this, start by adding the EntityFramework NuGet package to your project. Then, follow the examples below.

1. Setting Up Your DbContext

The DbContext class is the heart of EF. It manages your database connection and operations.

public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
}

Explanation:

  • The AppDbContext inherits from DbContext. This links your application to the database.
  • DbSet<Product> represents a table called Products.

2. Defining a Model Class

A model class maps to a table in the database.

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Explanation:

  • Each property corresponds to a column in the Products table.
  • The Id property serves as the primary key by convention.

3. Adding and Saving Data

To insert data into the database, create objects and add them to the DbSet.

using (var context = new AppDbContext())
{
    var product = new Product { Name = "Laptop", Price = 1200.50M };
    context.Products.Add(product);
    context.SaveChanges();
}

Explanation:

  • The Add method queues the object for insertion.
  • SaveChanges executes the SQL to insert the row.

4. Retrieving Data

Fetching records is simple with LINQ.

using (var context = new AppDbContext())
{
    var products = context.Products.ToList();
}

Explanation:

  • ToList eagerly loads all rows from the Products table into the products list.
  • You can also filter using LINQ queries, such as context.Products.Where(p => p.Price > 1000).

5. Updating Data

To update a record, retrieve it, modify, and call SaveChanges.

using (var context = new AppDbContext())
{
    var product = context.Products.FirstOrDefault(p => p.Id == 1);
    if (product != null)
    {
        product.Price = 1300.00M;
        context.SaveChanges();
    }
}

Explanation:

  • FirstOrDefault gets the first matching row or returns null if none exists.
  • Updating the Price and calling SaveChanges updates the database.

6. Deleting Data

Deleting is just as straightforward.

using (var context = new AppDbContext())
{
    var product = context.Products.FirstOrDefault(p => p.Id == 1);
    if (product != null)
    {
        context.Products.Remove(product);
        context.SaveChanges();
    }
}

Explanation:

  • Remove marks the object for deletion.
  • Similar to insertion or updates, changes are committed using SaveChanges.

Conclusion

Entity Framework is a powerful tool that can simplify database operations in your C# projects. Whether you're adding, reading, updating, or deleting data, you can do it effortlessly with EF. By eliminating the need for repetitive SQL queries, EF lets you focus on your application's business logic.

If you'd like to dive deeper, check out C# variables and their role in programming. Understanding these building blocks will give you a stronger foundation when working with EF models.

So, don’t hesitate—experiment with the examples above and see how EF can transform your coding workflow!

Previous Post Next Post

Welcome, New Friend!

We're excited to have you here for the first time!

Enjoy your colorful journey with us!

Welcome Back!

Great to see you Again

If you like the content share to help someone

Thanks

Contact Form