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");
});
}
CodePudding user response:
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);
}