it:ad:code_first:fluentapi

IT:AD:Code First:FluentAPI

Example:

public class OurDbContext : DbContext {

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Department>().Property(dp => dp.Name).IsRequired();
    modelBuilder.Entity<Manager>().HasKey(ma => ma.ManagerCode);
    modelBuilder.Entity<Manager>().Property(ma => ma.Name)
        .IsConcurrencyToken(true)
        .IsVariableLength()
        .HasMaxLength(20);
  }
}

You can break it up quite nicely as follows:

public class DepartmentTypeConfiguration : EntityTypeConfiguration<Department>
{
  public DepartmentTypeConfiguration()
  {
    Property(d => d.Name).
      IsRequired().
      HasMaxLength(50);
    ....
  }

}

WHich you can then add to your DbContext's OnModelBuilding method as follows:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

  //Add in...
  modelBuilder.Configurations.Add(new DepartmentTypeConfiguration());
  ...
  base.OnModelCreating(modelBuilder);
}
  • /home/skysigal/public_html/data/pages/it/ad/code_first/fluentapi.txt
  • Last modified: 2023/11/04 22:22
  • by 127.0.0.1