Unleashing the Power of EF Core: The Next Generation of Data Access in .NET

Unleashing the Power of EF Core: The Next Generation of Data Access in .NET

Entity Framework Core (EF Core) is a lightweight, extensible, and cross-platform version of the popular Entity Framework data access technology for .NET. EF Core provides a powerful object-relational mapping (ORM) capability that enables you to work with data in a database using C# or VB.NET code. With EF Core, you can easily perform common database operations such as CRUD (Create, Read, Update, and Delete) operations, querying, and database schema changes.

In this article, we'll explore the basics of using EF Core with a code example. We'll create a simple console application that uses EF Core to interact with a database. We'll use the Northwind sample database for this example.

To get started, you'll need to install the EF Core NuGet package. You can do this using the following command in the Package Manager Console in Visual Studio:

Install-Package Microsoft.EntityFrameworkCore

Next, we'll create a new console application project in Visual Studio. Once you've created the project, add the following code to the Program.cs file:

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace EFCoreDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new NorthwindContext())
            {
                context.Database.EnsureCreated();
                var customers = context.Customers.Take(10).ToList();
                foreach (var customer in customers)
                {
                    Console.WriteLine($"{customer.ContactName} - {customer.City}, {customer.Country}");
                }
            }
        }
    }

    public class NorthwindContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Northwind;Trusted_Connection=True;");
            optionsBuilder.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()));
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Customer>(entity =>
            {
                entity.ToTable("Customers");
                entity.HasKey(e => e.CustomerID);
                entity.Property(e => e.CustomerID).HasMaxLength(5);
            });
        }
    }

    public class Customer
    {
        public string CustomerID { get; set; }
        public string ContactName { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }
}

This code defines a Program class with a Main method that creates a new instance of the NorthwindContext class, which is our database context. We then call the EnsureCreated method to create the database if it doesn't already exist.

Next, we retrieve the first ten customers from the database using the Take and ToList methods, and print their contact name, city, and country to the console.

The NorthwindContext class is where we define our database schema and entity mappings. In this example, we define a DbSet<Customer> property that represents the "Customers" table in the database.

We then override the OnConfiguring method to specify the database connection string and to configure logging using the built-in ILogger interface. In this example, we're using SQL Server Express LocalDB.

Finally, we override the OnModelCreating method to define the mapping between our Customer class and the "Customers" table in the database. We specify that the primary key is the CustomerID

 

Related posts

Add comment

Loading