不同项目上的 EF Core fluent api 配置

EF Core fluent api configurations on different project

我有两个项目,DataDomain。在 Data 中,我有 Fluent API,我想将它的内容移动到 Domain。我怎样才能做到这一点?如果我使用的是数据库优先方法,是否可以配置 EF 来实现此目的?

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>(entity =>
            {
                entity.ToTable("Student", "dbo");

                entity.Property(e => e.CreatedDate)
                      .HasColumnType("datetime");

                entity.Property(e => e.IsEnabled)
                      .IsRequired()
                      .HasDefaultValueSql("((1))");

                entity.Property(e => e.Name)
                      .HasMaxLength(250);

                entity.Property(e => e.UpdatedDate)
                      .HasColumnType("datetime");
        });
}

Student 实体的配置移动到 Domain 项目中,进入一个单独的 class 实现 IEntityTypeConfiguration<T>

Allows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).

public class StudentConfiguration : IEntityTypeConfiguration<Student>
{
    public void Configure(EntityTypeBuilder<Student> builder)
    {
        builder
            .ToTable("Student", "dbo");
            
        builder.Property(e => e.CreatedDate).HasColumnType("datetime");
        
        // More rules go here.
    }
}

在您的 DbContext 中,您从 Domain 项目加载配置,如下所示。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .ApplyConfigurationsFromAssembly(typeof(Student).Assembly);

    base.OnModelCreating(modelBuilder);
}