这里默认使用sql server数据库 DBFirst
nuget引入程序集
-
Microsoft.EntityFrameworkCore
-
Microsoft.EntityFrameworkCore.SqlServer
-
Microsoft.EntityFrameworkCore.Design
-
Microsoft.EntityFrameworkCore.Tools
-
Microsoft.Extensions.Logging.Console
执行脚本
设置DAL层项目为启动项
工具 - nuget包管理器 - 程序包管理器控制台
输入以下指令并执行(用来连接数据库,创建DBContext)
Scaffold-DbContext "Data Source=DESKTOP-440HAKQ;Initial Catalog=Factory;Persist Security Info=True;User ID=sa;Password=你的密码" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -ContextDir Models -Context FactoryDbContext -Force
如果修改数据库之后想同步Model,只需要再次执行该命令即可,不过这样会覆盖原有文件,注意重新修改DbContext
FactoryDbContext 类就是service层可以使用的db上下文
修改appsettings.json
ConnectionStrings": {"FactoryDBString": "Data Source=DESKTOP-440HAKQ;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=你的密码"},
修改FactoryDbContext文件
public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){if (!optionsBuilder.IsConfigured){//根据配置文件读取数据库连接IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();string factorySqlStr = configuration.GetConnectionString("FactoryDBString");//使用日志记录sql语句optionsBuilder.UseLoggerFactory(MyLoggerFactory).EnableSensitiveDataLogging().UseSqlServer(factorySqlStr);}}
Autofac注入dbcontext
program中注入
buider.RegisterType<CustomerDbContext>().As<DbContext>();