• 欢迎光临~

ApplicationDbContext配置

开发技术 开发技术 2022-09-29 次浏览

一、appsetting.json 声明连接字符串

 "ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-DABHN6U\MSSQLSERVER2014;uid=sa;pwd=Lz38275292;database=SPA;MultipleActiveResultSets=true;"
  },

二、创建上下文类 ApplicationDbContext 

 public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions options) : base(options)
        {

        }

        public DbSet<MemberInfo> Members { get; set; }
        public DbSet<PostInfo> PostInfos { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.EnableSensitiveDataLogging(true);//错误信息中启用敏感数据记录
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            //设置组合主键
            List<string> keys = new List<string>();
            keys.Add(nameof(CardHistoryConsumptionInfo.会员编号));
            keys.Add(nameof(CardHistoryConsumptionInfo.流水号));
            keys.Add(nameof(CardHistoryConsumptionInfo.销售单明细ID));
            modelBuilder.Entity<CardHistoryConsumptionInfo>().HasKey(keys.ToArray());

            keys = new List<string>();
            keys.Add(nameof(StockInfo.年));
            keys.Add(nameof(StockInfo.月));
            keys.Add(nameof(StockInfo.会所编号));
            keys.Add(nameof(StockInfo.仓库编号));
            keys.Add(nameof(StockInfo.物品编号));
            modelBuilder.Entity<StockInfo>().HasKey(keys.ToArray());

            keys = new List<string>();
            keys.Add(nameof(AnotherNameInfo.表名));
            keys.Add(nameof(AnotherNameInfo.字段名));
            modelBuilder.Entity<AnotherNameInfo>().HasKey(keys.ToArray());

            keys = new List<string>();
            keys.Add(nameof(EmployeePerformanceInfo.流水号));
            keys.Add(nameof(EmployeePerformanceInfo.员工编号));
            modelBuilder.Entity<EmployeePerformanceInfo>().HasKey(keys.ToArray());

            // 配置表名映射
            modelBuilder.Entity<MemberInfo>().ToTable(MemberInfo.TableName);
          
        }

 三、注入服务 Program.cs

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

  

程序员灯塔
转载请注明原文链接:ApplicationDbContext配置
喜欢 (0)