1. CodeFirst: 方法一:用vs的PM命令来实现(注意:必须把默认项目设置成DbContenxt所在的项目,生成的数据库会在可以执行项目中 a. Add-Migration Init(名称,可以是任意值) b. Update-Database Init(用我们刚刚创建的名称迁移来更新数据库) 方法二:用cmd控制台输入命令来实现 a. dotnet ef migrations add Initial(名称,可以是任意值) b. dotnet ef database update(用我们刚刚创建的迁移来更新数据库) c. dotnet ef migrations add UserTableUpdateAccount(更新) 2.注入 在Web项目Startup类的ConfigureServices方法中注入DbContext: //const string connection = "Filename=./efcoredemo2.db"; //services.AddDbContext<RuntimeContext>(options => options.UseSqlite(connection)); //sqlite数据库 //services.AddDbContext<RuntimeContext>(options => options.UseSqlServer("DefaultConnection")); //sql数据库 //连接池方式注入 services.AddDbContextPool<RuntimeContext>(options => options.UseSqlite(GetConnection())); 3.初始化数据 与EF Core 1.x不同的是,2.0是在Program.cs里的Main方法里(1.x是在Startup.cs中的Configure方法中)添加初始化方法。 public static void Main(string[] args) { var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { SeedData.Initialize(services); } catch(Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred seeding the DB"); } } host.Run(); })
转载于:https://www.cnblogs.com/dxx8575/p/8288459.html