1. 程式人生 > >ASP.NET Core中使用EF Core(MySql)Code First

ASP.NET Core中使用EF Core(MySql)Code First

mys lambda core context gin etc roo nim 建數據庫

⒈添加依賴

  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         }

⒌使用遷移創建數據庫

  第一種方式:

  第二種方式:

ASP.NET Core中使用EF Core(MySql)Code First