ASP.NET Core中使用EF Core(MySql)Code First
⒈添加依赖
MySql.Data.EntityFrameworkCore
⒉在appsettings.json配置文件中配置数据库连接字符串
1 { 2 "Logging": { 3 "LogLevel": { 4 "Default": "Warning" 5 } 6 }, 7 "ConnectionStrings": { 8 "MySqlConnection": "server=localhost;port=3306;database=blog;user=root;password=admin" 9 }, 10 "AllowedHosts": "*" 11 }
⒊编写数据表实体类及上下文
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 6 namespace NewDb.Models 7 { 8 public class Blog 9 { 10 public int BlogId { get; set; } 11 public string Url { get; set; } 12 13 public ICollection<Post> Posts { get; set; } 14 15 } 16 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 6 namespace NewDb.Models 7 { 8 public class Post 9 { 10 public int PostId { get; set; } 11 public string Title { get; set; } 12 public string Content { get; set; } 13 14 public int BlogId { get; set; } 15 public Blog Blog { get; set; } 16 } 17 }
1 using Microsoft.EntityFrameworkCore; 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Threading.Tasks; 6 7 namespace NewDb.Models 8 { 9 public class BloggingDbContext : DbContext 10 { 11 public BloggingDbContext(DbContextOptions<BloggingDbContext> options) : base(options) { } 12 13 public DbSet<Blog> Blogs { get; set; } 14 public DbSet<Post> Posts { get; set; } 15 } 16 }
⒋使用依赖注入将上下文注册为服务
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 }
⒌使用迁移创建数据库
第一种方式:"Visual Studio 2019" >“工具”>“NuGet 包管理器”>“程序包管理器控制台”,执行以下命令
1 Add-Migration InitialCreate -v #搭建迁移基架,以便为模型创建一组初始表 2 Update-Database -v #创建数据库并向其应用新的迁移
第二种方式:使用.Net Core CLI,执行以下命令
1 dotnet ef migrations add InitialCreate -v #搭建迁移基架,以便为模型创建一组初始表 2 dotnet ef database update -v #创建数据库并向其应用新的迁移