Getting started with Entity Framework Core: Building a Sample Project

Getting started with Entity Framework Core: Building a Sample Project

Jul 10, 2023Β·

4 min read

Introduction:

Entity Framework Core (EF Core) is a powerful Object-Relational Mapping (ORM) framework for .NET developers. With its rich features and versatility, EF Core simplifies database interactions, allowing developers to focus on application logic rather than complex data access operations. In this blog post, we will explore EF Core by building a sample project, and delve into its benefits and other essential details.

What is Entity Framework Core (EF Core)?

Entity Framework Core is a modern, lightweight, and cross-platform ORM framework developed by Microsoft. It enables developers to work with databases using .NET objects, eliminating the need for writing raw SQL queries. EF Core provides a higher-level abstraction, allowing seamless interaction with various database providers, such as SQL Server, PostgreSQL, MySQL, SQLite, and more.

Setting up the sample project:
To get started with EF Core, let's build a simple project that manages a list of blog posts.

Follow these steps:

  1. Create a new .NET Core Console project in your preferred IDE. Here I have used Visual Studio with .NET 6 framework.

  2. Install the Entity Framework Core packages via NuGet (using the package manager console in Visual Studio).

    2.1. EF Core database provider (I have used SQLite for its simplicity)

    2.2. EF Core Tools

     Install-Package Microsoft.EntityFrameworkCore.Sqlite
     Install-Package Microsoft.EntityFrameworkCore.Tools
    
  3. Define your data model

     public class Blog
     {
         public int BlogId { get; set; }
         public string Url { get; set; }
    
         public List<Post> Posts { get; } = new();
     }
    
     public class Post
     {
         public int PostId { get; set; }
         public string Title { get; set; }
         public string Content { get; set; }
    
         public int BlogId { get; set; }
         public Blog Blog { get; set; }
     }
    
  4. Create a DbContext class that represents your database context:

     public class BloggingContext : DbContext
     {
         public DbSet<Blog> Blogs { get; set; }
         public DbSet<Post> Posts { get; set; }
    
         public string DbPath { get; }
    
         public BloggingContext()
         {
             var folder = Environment.SpecialFolder.LocalApplicationData;
             var path = Environment.GetFolderPath(folder);
             DbPath = System.IO.Path.Join(path, "blogging.db");
         }
    
         // The following configures EF to create a Sqlite database file in the
         // special "local" folder for your platform.
         protected override void OnConfiguring(DbContextOptionsBuilder options)
         {
             if (!options.IsConfigured)
             {
                 options
                     .LogTo(message => Debug.WriteLine(message))
                     .EnableSensitiveDataLogging();
    
                 options.UseSqlite($"Data Source={DbPath}");
             }
         }
     }
    
  5. Add Migrations:
    Run the below commands in the package manager console.

     Add-Migration InitialCreate //Creating migration(SQL) scripts
     Update-Database //Run the above SQL scripts in database
    
  6. Perform database operations:

     using var db = new BloggingContext();
    
     // Note: This sample requires the database to be created before running.
     Console.WriteLine($"Database path: {db.DbPath}.");
    
     // Create
     Console.WriteLine("Inserting a new blog");
     db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
     db.SaveChanges();
    
     // Read
     Console.WriteLine("Querying for a blog");
     var blog = db.Blogs
         .OrderBy(b => b.BlogId)
         .First();
    
     // Update
     Console.WriteLine("Updating the blog and adding a post");
     blog.Url = "https://devblogs.microsoft.com/dotnet";
     blog.Posts.Add(
         new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" });
     db.SaveChanges();
    
     // Delete
     Console.WriteLine("Delete the blog");
     db.Remove(blog);
     db.SaveChanges();
    

    From the above examples, you can see that we are using EF Core to read, write and update the data in the database without writing any SQL scripts.

    Benefits of Entity Framework Core:

    1. Productivity: EF Core enables rapid application development by providing a high-level abstraction and eliminating the need to write repetitive SQL queries. Its intuitive APIs, such as LINQ, allow developers to express complex queries and database operations in a more readable and maintainable manner.

    2. Database Independence: With EF Core, you can easily switch between different database providers without modifying your application code significantly. This flexibility allows developers to choose the most suitable database solution for their project requirements.

    3. Automatic Schema Migrations: EF Core's migration feature simplifies the process of evolving the database schema over time. It automatically generates SQL scripts to create, update, or delete database objects based on changes made to the data model, eliminating the manual effort of managing database scripts.

    4. Performance Optimization: EF Core provides various performance optimization techniques, such as query caching, lazy loading, and eager loading, to enhance the performance of database operations. These optimizations help minimize roundtrips to the database and improve the overall response time of your application.

    5. Testability: EF Core facilitates unit testing by allowing developers to mock the database context and perform tests against an in-memory database. This capability ensures that your data access logic can be thoroughly tested without requiring a real database connection.

Conclusion:

Entity Framework Core empowers developers to build efficient and scalable database applications with ease. In this blog post, we explored EF Core by creating a sample project and discussed its numerous benefits, including increased productivity, database independence, automatic schema migrations, performance optimization, and testability. EF Core continues to evolve, offering a robust set of tools and features to streamline data access in the .NET ecosystem.

Embrace the power of Entity Framework Core and unlock the full potential of your database-driven applications!

Happy coding with EF Core!