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

时间:2023-03-09 23:53:23
ASP.NET Core中使用EF Core(MySql)Code First

⒈添加依赖

  MySql.Data.EntityFrameworkCore

⒉在appsettings.json配置文件中配置数据库连接字符串

 {
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"MySqlConnection": "server=localhost;port=3306;database=blog;user=root;password=admin"
},
"AllowedHosts": "*"
}

⒊编写数据表实体类及上下文

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace NewDb.Models
{
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } public ICollection<Post> Posts { get; set; } }
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace NewDb.Models
{
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; } public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
 using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace NewDb.Models
{
public class BloggingDbContext : DbContext
{
public BloggingDbContext(DbContextOptions<BloggingDbContext> options) : base(options) { } public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
}

⒋使用依赖注入将上下文注册为服务

         public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); var connection = Configuration["ConnectionStrings:MySqlConnection"]; services.AddDbContext<BloggingDbContext>(options =>
{
options.UseMySQL(connection);
});
}

⒌使用迁移创建数据库

  第一种方式:"Visual Studio 2019" >“工具”>“NuGet 包管理器”>“程序包管理器控制台”,执行以下命令

 Add-Migration InitialCreate -v #搭建迁移基架,以便为模型创建一组初始表
Update-Database -v #创建数据库并向其应用新的迁移

  第二种方式:使用.Net Core CLI,执行以下命令

 dotnet ef migrations add InitialCreate -v #搭建迁移基架,以便为模型创建一组初始表
dotnet ef database update -v #创建数据库并向其应用新的迁移