ASP.NET Core中使用EF Core(MySql)Database First
⒈创建数据库,在数据中执行以下脚本。
1 CREATE DATABASE Blogging; 2 3 USE Blogging; 4 5 CREATE TABLE Blog ( 6 BlogId int not null PRIMARY key auto_increment, 7 Url text not null 8 ); 9 10 CREATE TABLE Post ( 11 PostId int NOT NULL PRIMARY key auto_increment, 12 BlogId int NOT NULL, 13 Content text, 14 Title varchar(100), 15 CONSTRAINT FK_Post_Blog_BlogId FOREIGN KEY(BlogId) REFERENCES Blog(BlogId) ON DELETE CASCADE 16 ); 17 18 INSERT INTO Blog (Url) VALUES 19 ('http://blogs.msdn.com/dotnet'), 20 ('http://blogs.msdn.com/webdev'), 21 ('http://blogs.msdn.com/visualstudio')
⒉添加依赖
MySql.Data.EntityFrameworkCore
⒊实施反向工程,基于现有数据库创建数据表实体类及上下文。
第一种方式:"Visual Studio 2019" >“工具”>“NuGet 包管理器”>“程序包管理器控制台”,执行以下命令(最好提前编译以下项目,否则以下命令可能执行不成功)
1 #Scaffold-DbContext "数据库连接字符串" 数据库提供程序 -OutputDir 输出文件夹 2 Scaffold-DbContext "server=localhost;port=3306;database=blogging;user=root;password=admin;" MySql.Data.EntityFrameworkCore -OutputDir Models
第二种方式:使用.Net Core CLI,执行以下命令
1 #dotnet ef dbcontext scaffold "数据库连接字符串" 数据库提供程序 -o 输出文件夹 2 dotnet ef dbcontext scaffold "server=localhost;port=3306;database=blogging;user=root;password=admin;" MySql.Data.EntityFrameworkCore -o Models
⒋使用依赖注入将上下文注册为服务
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.Configure<CookiePolicyOptions>(options => 4 { 5 // This lambda determines whether user consent for non-essential cookies is needed for a given request. 6 options.CheckConsentNeeded = context => true; 7 options.MinimumSameSitePolicy = SameSiteMode.None; 8 }); 9 10 11 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 12 13 var connection = Configuration["ConnectionStrings:MySqlConnection"]; 14 15 services.AddDbContext<BloggingDbContext>(options => 16 { 17 options.UseMySQL(connection); 18 }); 19 }