本文演示如何使用 Entity Framework Core 和 Fluent API 配置数据库上下文类 NorthwindDbContext,以及如何使用 Fluent API 配置实体之间的'一对多'关系。

using Microsoft.EntityFrameworkCore;
using Northwind.Models;

namespace Northwind.Data
{
    public class NorthwindDbContext : DbContext
    {
        public NorthwindDbContext(DbContextOptions<NorthwindDbContext> options) : base(options)
        {
        }

        // DbSet for each entity
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Configure one-to-many relationship between Category and Product
            modelBuilder.Entity<Product>()
                .HasOne(p => p.Category)
                .WithMany(c => c.Products)
                .HasForeignKey(p => p.CategoryId);

            // Configure other entity configurations here

            base.OnModelCreating(modelBuilder);
        }
    }
}

在上述代码中,我们定义了一个名为 NorthwindDbContext 的数据库上下文类,它继承自 DbContext 类。我们在构造函数中通过 DbContextOptions 类型的参数来配置数据库连接字符串等选项。

在这个类中,我们定义了一个 DbSet 属性来表示每个实体,例如 Categories 和 Products。这些属性将用于查询和操作数据库中的数据。

在 OnModelCreating 方法中,我们使用 Fluent API 来配置实体之间的关系。在这个例子中,我们配置了一个'一对多'的关系,其中一个类别可以有多个产品,而一个产品只能属于一个类别。我们使用 HasOne 和 WithMany 方法来指定关系,使用 HasForeignKey 方法来指定外键。

最后,我们调用了基类的 OnModelCreating 方法来应用我们的配置。

使用 Entity Framework Core 和 Fluent API 配置数据库上下文类和一对多关系

原文地址: https://www.cveoy.top/t/topic/oiqL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录