A Step-by-Step Guide to Using Entity Framework with .NET Core

A Step-by-Step Guide to Using Entity Framework with .NET Core


Are you a .NET developer looking to simplify data access in your applications? Entity Framework Core (EF Core) is here to make your life easier. EF Core is a powerful Object-Relational Mapper (ORM) that allows you to interact with your database using C# instead of raw SQL, streamlining development and boosting productivity. In this article, I'll walk you through using EF Core step-by-step with .NET Core so you can get started building data-driven applications with ease.

Step 1: Setting Up Your Project

To begin, you'll need a .NET Core project to work with. If you haven't already, create a new .NET Core application using the command line:

> dotnet new webapi -n EFCoreDemo        

This command will create a new ASP.NET Core Web API project named "EFCoreDemo." Once you've got your project set up, you'll need to add the necessary Entity Framework Core packages. You can do this by running:

> dotnet add package Microsoft.EntityFrameworkCore
> dotnet add package Microsoft.EntityFrameworkCore.SqlServer        

The above commands add EF Core itself along with support for SQL Server. You can also use different providers, depending on your database.

Step 2: Defining Your Data Model

With your project set up, the next step is to define the data model. In EF Core, your data model is usually represented by C# classes, known as POCOs (Plain Old CLR Objects). Here's an example of a simple model representing a "Product":

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

This class defines the properties for the Product table in your database.

Step 3: Creating the Database Context

The next step is to create a DbContext class, which will serve as the bridge between your data model and the database. Add a new class called AppDbContext to your project:

using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    public DbSet<Product> Products { get; set; }
}        

The AppDbContext class includes a DbSet<Product> property, which maps to a Products table in your database.

Step 4: Configuring the Database Connection

To configure EF Core to use a SQL Server database, you'll need to set up the connection string in appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "Server=your_server;Database=EFCoreDemo;User Id=your_username;Password=your_password;"
}        

Now, register the AppDbContext in the Startup.cs file (or Program.cs if using newer versions of .NET):

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));        

This line sets up the dependency injection for your context, allowing you to use AppDbContext throughout your application.

Step 5: Running Migrations

With your data model and context ready, the next step is to create the database tables. EF Core migrations make this easy. Run the following commands to add and apply a migration:

> dotnet ef migrations add InitialCreate
> dotnet ef database update        

The InitialCreate migration represents the changes to your data model, and the database update command applies those changes to your database, creating the necessary tables.

Step 6: Using the Database in Your Code

Finally, you can start using the AppDbContext to interact with your database. Here’s an example of how to add a new product:

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

You can also use LINQ to query the database:

var products = context.Products.Where(p => p.Price < 1000).ToList();        

Wrapping Up

Entity Framework Core is an incredibly powerful tool for .NET developers, allowing you to abstract away the complexities of raw SQL and focus on your application's logic. By following this step-by-step guide, you’ve learned how to set up EF Core, define your data model, and interact with your database effortlessly.

Ready to try it out? Add EF Core to your next .NET project and start building amazing data-driven applications!

I'd love to hear your thoughts. Have you used EF Core in your projects before, or are you planning to? Drop a comment below and share your experiences or any challenges you've faced!

Sajal Limbu

Senior Developer at PROCIT BV

6mo

Insightful

Like
Reply
Himanshu Rajput

(Immediate joiner) Experienced Software Developer Expert in Building Scalable Solutions & Leading Development Teams

6mo

Interesting

Like
Reply
Shayar Shrestha

Software Engineer (.NET) | Master's in Computer Science | Data Science Enthusiast | AI & Machine Learning Learner

6mo

Very informative

Like
Reply

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics