创建 Web 项目





删除无用配置及Demo
修改Properties文件夹下的launchSettings.json
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"EFGetStarted": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
删除Controller下的WeatherForecastController.cs和根目录下的WeatherForecast.cs


添加实体
新建Models文件夹

在Models文件夹下新建类
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public Blog Blog { get; set; }
}
public class AuditEntry
{
public int AuditEntryId { get; set; }
public string Username { get; set; }
public string Action { get; set; }
}

添加数据库上下文
新建Data文件夹,在其中添加数据库上下文
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}

此时程序会标红报错,这是因为缺少依赖项造成的
打开Nuget包管理器,搜索MySql.EntityFrameworkCore并安装

在程序中导入即可
using Microsoft.EntityFrameworkCore;
namespace EFGetStarted.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}
在数据库上下文中为每个实体实在DbSet实例
using EFGetStarted.Models;
using Microsoft.EntityFrameworkCore;
namespace EFGetStarted.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Blog> blogs { get; set; }
public DbSet<Post> posts { get; set; }
public DbSet<AuditEntry> auditEntries { get; set; }
}
}
注册数据库上下文
因为我们要使用MySQL数据库,所以需要配置MySQL的连接信息
在appsettings.json配置文件中添加:
"ConnectionStrings": {
"MysqlConnection": "Data Source=127.0.0.1;Database=ef-mysql-api;User ID=root;Password=123456789;pooling=true;port=3306;sslmode=none;CharSet=utf8;"
},
修改后为

在Startup.cs中注册数据库上下文
// 将服务添加到DI容器中
public void ConfigureServices(IServiceCollection services)
{
// 读取数据库连接字符串
var connection = Configuration.GetConnectionString("MysqlConnection");
// 注册数据库上下文
services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(connection));
services.AddControllers();
}
创建第一个迁移
dotnet ef migrations add InitialCreate

安装Microsoft.EntityFrameworkCore.Design

再次运行

此时会多出一个Migrations文件夹

使用数据迁移创建在数据库中建表
dotnet ef database update
此时数据库中就建表成功了

修改实体模型
修改Blog的属性
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
public DateTime CreatedTimestamp { get; set; }
}
执行创建迁移
dotnet ef migrations add changebolg1
dotnet ef migrations add 描述性名称
更新数据库
dotnet ef database update
8923

被折叠的 条评论
为什么被折叠?



