EFCore (Fluent API) 分组配置

前言: 真实入手项目的时候如果向 https://www.cnblogs.com/tlfe/p/18284025 中 第5点这么给每个表中的字段配置,不方便后期维护和管理
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)
    {
        builder.HasComment("商品信息表");

        //手动设置主键: 默认会以表名+Id或者Id为主键,如果不是这两种情况,就不会默认设置为主键
        builder.HasKey(e => e.Id).HasName("pk_prminkey"); // 默认HasName 是 pk_Id

        //builder.Property(p => p.Id)
        //    .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. 在 BingBDContext.cs 类文件中加入配置

public class BingBDContext : DbContext
{protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("链接数据库链接");
    }
    public DbSet<Book> Books { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //批量添加实体配置
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(BookEntitlyConfig).Assembly);
    }
}

 

posted @ 2024-07-05 16:22  龙卷风吹毁停车场  阅读(7)  评论(0编辑  收藏  举报