EFCore

Entity Framework Core (EF Core) is a modern, open-source, and cross-platform Object-Relational Mapper (ORM) for .NET. It allows developers to work with a database using .NET objects, eliminating most of the data-access code that developers usually need to write. EF Core supports LINQ queries, change tracking, updates, and schema migrations.

  • Productivity: EF Core simplifies data access by reducing the amount of boilerplate code required for database operations.

  • LINQ Support: It allows you to write database queries using LINQ, which is type-safe and easier to understand.

  • Cross-platform: EF Core works on multiple platforms, including Windows, Linux, and macOS.

  • Migrations: It helps manage database schema changes through a migration API.


  • Install EF Core: You can install EF Core via NuGet Package Manager or the Package Manager Console:

    Install-Package Microsoft.EntityFrameworkCore
    Install-Package Microsoft.EntityFrameworkCore.SqlServer
  • Set Up the Model and DbContext: Define your data model and the DbContext that manages database interactions.

  • Perform Database Operations: Use EF Core's DbContext to query and save data to the database.

Example with EF Core

BlogModel.cs

public class BlogModel
{
    public int BlogId { get; set; }
    public string BlogTitle { get; set; }
    public string BlogAuthor { get; set; }
    public string BlogContent { get; set; }
}

BlogContext.cs

EF Core Example

  1. Constructor

Summary: The constructor initializes the class with a BlogContext object, which is used to manage database interactions.

  1. Read Method

Summary: This method retrieves all blog entries from the Blogs DbSet, converts the results to a list of BlogModel objects, and prints each blog's data to the console.

  1. Edit Method

Summary: This method retrieves a specific blog entry based on the provided ID, prints the details if found, or indicates that no data was found.

  1. Create Method

Summary: This method creates a new blog entry, adds it to the Blogs DbSet, and saves the changes to the database.

  1. Update Method

Summary: This method updates an existing blog entry based on the provided ID, title, author, and content, and saves the changes to the database.

  1. Delete Method

Summary: This method deletes a blog entry from the Blogs DbSet based on the provided ID, and saves the changes to the database.

Helper Method: Convert DataTable to List of BlogModel

In EF Core, you don't need a helper method to convert a DataTable to a list of models because EF Core handles this conversion internally.

Summary: By using EF Core, you can simplify database operations while maintaining strong typing and relationships between your data models. EF Core's support for LINQ queries, change tracking, updates, and migrations makes it a powerful tool for managing database interactions in .NET applications.

Last updated