Entity Framework Core (EF Core)

Entity Framework Core (EF Core) is a modern Object-Relational Mapper (ORM) for .NET that allows developers to interact with databases using C# objects instead of writing raw SQL queries.

It simplifies data access by providing built-in support for CRUD operations, database migrations, relationships, and LINQ-based queries.

EF Core is widely used in ASP.NET Core applications for building scalable, data-driven web applications efficiently and with less code.

What You Will Learn

What is Entity Framework Core?

Entity Framework Core is an open-source ORM framework that acts as a bridge between your application and the database.

Instead of writing SQL queries manually, developers work with C# classes and objects that represent database tables.

Example: Basic Model


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

DbContext Example


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

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer("YourConnectionStringHere");
    }
}

CRUD Operations

Create


var product = new Product { Name = "Laptop", Price = 1200 };

context.Products.Add(product);
context.SaveChanges();

Read


var products = context.Products.ToList();

Update


var product = context.Products.First();
product.Price = 1500;

context.SaveChanges();

Delete


var product = context.Products.First();
context.Products.Remove(product);

context.SaveChanges();

Database Migrations

Migrations allow you to update your database schema without losing data.


dotnet ef migrations add InitialCreate
dotnet ef database update

Relationships in EF Core

EF Core supports different types of relationships such as one-to-one, one-to-many, and many-to-many relationships.

Why Use EF Core?

Best Practices

Conclusion

Entity Framework Core is a powerful tool for modern .NET development. It simplifies database access, improves productivity, and integrates seamlessly with ASP.NET Core applications.

By mastering EF Core, you can build scalable, efficient, and maintainable data-driven applications.

Related Tutorials