public class Book { public int id { get; set; } public string name { get; set; } public double money { get; set; } } public class Person { public int id { get; set; } public string name { get; set; } public int age { get; set; } public string sex { get; set;} }
配置类:
1 2 3 4 5 6 7 8 9 10 11
public class BookEntityConfig : IEntityTypeConfiguration<Book> { public void Configure(EntityTypeBuilder<Book> builder) { builder.ToTable("T_Books"); builder.Property(e=>e.name).HasMaxLength(50).IsRequired();//设置书名最大长度50,不允许为空 } } public class PersonEntityConfig : IEntityTypeConfiguration<Person> { public void Configure(EntityTypeBuilder<Person> builder) { builder.ToTable("T_Persons"); } }
DbContext类:
1 2 3 4 5 6 7 8 9 10 11 12
public class MyDbContext:DbContext { public DbSet<Book> Books { get; set; } public DbSet<Person> Persons { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer("数据库连接字符串"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly); } }