简体   繁体   中英

EF Core fluent api configurations on different project

I have two projects, Data and Domain . In Data I have the Fluent API, I want to move it's contents to Domain . How can I do this? Is there a way to configure EF to make this if I'm using a database-first approach?

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

Move the configuration of the Student entity to the Domain project into a separate class implemententing 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.
    }
}

In your DbContext you load the configurations from the Domain project, like below for example.

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

    base.OnModelCreating(modelBuilder);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM