一、自定义配置类实现IEntityTypeConfiguration<T>接口
public class SecurityConfiguration:IEntityTypeConfiguration<Security> { public void Configure(EntityTypeBuilder<Security> builder) { builder.Property(e => e.Id).HasColumnName("SecurityId"); builder.Property(e => e.UserName).IsRequired().HasMaxLength(100); builder.Property(e => e.User).IsRequired().HasMaxLength(50); builder.Property(e => e.Password).IsRequired().HasMaxLength(200); builder.Property(e => e.Role) .IsRequired() .HasMaxLength(15) .HasConversion( e=>e.ToString(), e=>(RoleType)Enum.Parse(typeof(RoleType),e)); } }
二、在DbContext中通过程序集加载
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); }