EFCore (Fluent API) 分组配置
前言: 真实入手项目的时候如果向 https://www.cnblogs.com/tlfe/p/18284025 中 第5点这么给每个表中的字段配置,不方便后期维护和管理
1. 在根目录创建一个EntityConfig文件夹
1. 在根目录创建一个EntityConfig文件夹
2. 根据实体类创建一个BookEntityConfig.cs类文件
namespace WebApplication1.Models { public class Book { /// <summary> /// id /// </summary> public int Id { get; set; } /// <summary> /// 书本名称 /// </summary> public string Name { get; set; } /// <summary> /// 价格 /// </summary> public decimal Price { get; set; } /// <summary> /// 所属类型 /// </summary> public string Type { get; set; } /// <summary> /// 添加时间 /// </summary> public DateTime CreatTime { get; set; } } }
public class BookEntitlyConfig : IEntityTypeConfiguration<Book> { public void Configure(EntityTypeBuilder<Book> builder) {//手动设置主键: 默认会以表名+Id或者Id为主键,如果不是这两种情况,就不会默认设置为主键 builder.HasKey(e => e.Id).HasName("pk_prminkey"); // 默认HasName 是 pk_Id //builder.Property(p => p.Id)
// .UseIdentityColumn(1000,1) //自增从1000开始,每次加1 // .ValueGeneratedNever() //取消自增 // .ValueGeneratedOnAdd(); //启用自增 //设置外键: 需要再book实体类中添加一个 public int PostId {get;set;} //builder.HasOne<Post>().WithMany().HasForeignKey(e => e.PostId); //这是索引: 我这点将时间设置为索引,并取一个索引名字 //builder.HasIndex(e => new {e.CreatTime,e.Name} ).HasDatabaseName("idx_create_time"); //复合索引 //builder.HasIndex(e => e.CreatTime).HasDatabaseName("idx_create_time").IsUnique(); //唯一索引 builder.HasIndex(e => e.Name).IncludeProperties(e => new { e.CreatTime, e.Price }); //覆盖索引 //配置表中的属性 builder.Property(p => p.Name) //.IsRequired() .HasComment("商品名") .HasColumnType("varchar(100)") .HasColumnName("SpingName"); builder.Property(p => p.Price) //.IsRequired() .HasComment("价格") .HasColumnType("decimal"); builder.Property(p => p.Type) //.IsRequired() .HasComment("玄幻") .HasColumnType("varchar(50)"); builder.Property(p => p.CreatTime) .HasDefaultValueSql("getdate()"); } }
3. 在 ApplicationContent.cs 类文件中加入配置
public class ApplicationContent: DbContext { public ApplicationContent(DbContextOptions<ApplicationContent> option):base(option) { } /// <summary> /// 用户表 /// </summary> public DbSet<Users> Users { get; set; } /// <summary> /// 文章信息表 /// </summary> public DbSet<Publish> Publishes { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { //应用所有配置 modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); } }
4. 在Program.cs注册
builder.Services.AddDbContextPool<ApplicationContent>(option => { option.UseSqlServer(builder.Configuration.GetConnectionString("connStr")); });
5.appsettings.json配置
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "ConnectionStrings": { "connStr": "你的数据库链接字符串" }, "AllowedHosts": "*" }