首先,我们需要在项目中添加 Entity Framework Core 的依赖项和相关工具。可以通过 NuGet 包管理器或者手动添加引用实现。

接着,我们需要定义数据库上下文类 NorthwindDbContext,该类继承自 DbContext 类,并且包含对应数据库中每个实体的 DbSet 属性。

using Microsoft.EntityFrameworkCore;

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

        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }
        // 其他实体的 DbSet 属性
    }
}

接着,我们需要实现 Fluent API 配置实体之间的关系,例如 Category 和 Product 之间的一对多关系。

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Northwind.Models
{
    public class CategoryConfiguration : IEntityTypeConfiguration<Category>
    {
        public void Configure(EntityTypeBuilder<Category> builder)
        {
            builder.HasKey(c => c.CategoryID);

            builder.HasMany(c => c.Products)
                .WithOne(p => p.Category)
                .HasForeignKey(p => p.CategoryID);
        }
    }
}

上述代码中,我们定义了一个 CategoryConfiguration 类,实现了 IEntityTypeConfiguration 接口,该接口包含一个 Configure 方法,其中通过 builder 对象实现对 Category 实体的配置。

在 Configure 方法中,我们通过 builder 对象的 HasKey 方法指定了 Category 实体的主键为 CategoryID 属性。

接着,我们通过 builder 对象的 HasMany 方法指定了 Category 实体和 Product 实体的一对多关系。具体来说,Category 实体包含多个 Product 实体,而 Product 实体只属于一个 Category 实体。

通过 HasMany 方法的参数,我们指定了 Category 实体的导航属性 Products,而通过 WithOne 方法的参数,我们指定了 Product 实体的导航属性 Category。

最后,通过 HasForeignKey 方法指定了 Product 实体的外键 CategoryID,该外键引用了 Category 实体的主键 CategoryID。

在 NorthwindDbContext 中,我们需要将 CategoryConfiguration 类添加到 OnModelCreating 方法中的 modelBuilder 参数中。

using Microsoft.EntityFrameworkCore;

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

        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }
        // 其他实体的 DbSet 属性

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new CategoryConfiguration());
            // 其他实体的配置类
        }
    }
}

通过调用 modelBuilder 对象的 ApplyConfiguration 方法,我们可以将 CategoryConfiguration 类添加到模型构建器中,从而实现对 Category 实体的配置。

以上就是基于 Entity Framework Core 模型配置好数据库上下文类 NorthwindDbContext,并且通过 Fluent API 配置实体之间的一对多关系的示例代码。

Entity Framework Core 模型配置:数据库上下文类和一对多关系

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

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