这里默认使用sql server数据库 DBFirst
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上下文
ConnectionStrings": {
"FactoryDBString": "Data Source=DESKTOP-440HAKQ;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=你的密码"
},
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);
}
}
program中注入
buider.RegisterType<CustomerDbContext>().As<DbContext>();