Introduction

Entity Framework Core (EF Core) is a powerful Object-Relational Mapper (ORM) that allows developers to interact with databases using .NET objects. It simplifies data access and manipulation by enabling developers to work with data in the form of objects and properties, rather than tables and columns. This post will guide you through setting up EF Core in a C# application, creating a model, and performing basic CRUD (Create, Read, Update, Delete) operations.

Setting Up Entity Framework Core

To get started with EF Core, you need to install the necessary NuGet packages and configure your project.

  1. Create a Console App:
  • In Visual Studio, create a new Console App project named “EFCoreExample”.
  1. Install EF Core Packages:
  • Open the NuGet Package Manager Console (Tools > NuGet Package Manager > Package Manager Console).
  • Run the following commands:
    Install-Package Microsoft.EntityFrameworkCore Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools

Creating the Model and DbContext

In EF Core, you define the shape of your data using model classes. The DbContext class manages the database connection and provides methods for querying and saving data.

Example: Defining the Model and DbContext

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;

namespace EFCoreExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            using (var context = new AppDbContext())
            {
                // Ensure database is created
                context.Database.EnsureCreated();

                // Create and save a new Blog
                var blog = new Blog { Url = "http://sample.com" };
                context.Blogs.Add(blog);
                context.SaveChanges();

                // Query and display blogs
                var blogs = context.Blogs;
                Console.WriteLine("All blogs in the database:");
                foreach (var b in blogs)
                {
                    Console.WriteLine($" - {b.Url}");
                }
            }
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
        public List<Post> Posts { get; set; }
    }

    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; }
    }

    public class AppDbContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFCoreExampleDb;Trusted_Connection=True;");
        }
    }
}

Explanation:

  • Blog and Post Classes: Represent the data structure.
  • AppDbContext: Manages the database connection and provides methods for interacting with the data.
  • OnConfiguring: Configures the database connection string.

Performing CRUD Operations

Create Operation: Adding a new record to the database.

var blog = new Blog { Url = "http://sample.com" };
context.Blogs.Add(blog);
context.SaveChanges();

Read Operation: Querying data from the database.

var blogs = context.Blogs.ToList();
foreach (var b in blogs)
{
    Console.WriteLine($" - {b.Url}");
}

Update Operation: Modifying an existing record.

var blog = context.Blogs.First();
blog.Url = "http://updatedsample.com";
context.SaveChanges();

Delete Operation: Removing a record from the database.

var blog = context.Blogs.First();
context.Blogs.Remove(blog);
context.SaveChanges();

Full Example Code

Here is the complete code for setting up EF Core, defining the model, and performing CRUD operations:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;

namespace EFCoreExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            using (var context = new AppDbContext())
            {
                // Ensure database is created
                context.Database.EnsureCreated();

                // Create and save a new Blog
                var blog = new Blog { Url = "http://sample.com" };
                context.Blogs.Add(blog);
                context.SaveChanges();

                // Query and display blogs
                var blogs = context.Blogs.ToList();
                Console.WriteLine("All blogs in the database:");
                foreach (var b in blogs)
                {
                    Console.WriteLine($" - {b.Url}");
                }

                // Update the first blog
                var firstBlog = context.Blogs.First();
                firstBlog.Url = "http://updatedsample.com";
                context.SaveChanges();
                Console.WriteLine($"Updated blog URL to: {firstBlog.Url}");

                // Delete the first blog
                context.Blogs.Remove(firstBlog);
                context.SaveChanges();
                Console.WriteLine("Deleted the first blog");
            }
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
        public List<Post> Posts { get; set; }
    }

    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; }
    }

    public class AppDbContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFCoreExampleDb;Trusted_Connection=True;");
        }
    }
}

Conclusion

Entity Framework Core simplifies data access and manipulation in C# applications by allowing developers to work with data using objects and properties. By understanding how to set up EF Core, define models, and perform CRUD operations, you can efficiently manage database interactions in your applications.

Similar Posts