创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

时间:2022-05-27 22:51:20

创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

创建数据模型类(POCO类)

Models文件夹下添加一个User类:

namespace MyFirstApp.Models
{
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Bio { get; set; }
}
}

除了你期望的用来构建Movie模型的属性外,将作为数据库主键的ID字段是必须的。

安装Entity Framework Core MySQL相关依赖项

创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

注:其中"MySql.Data.EntityFrameworkCore": "7.0.6-ir31",要7.0.6以上版本。

Missing implementation for running EntityFramework Core code first migration

创建Entity Framework Context数据库上下文

Models文件夹下添加一个UserContext类:

/// <summary>
/// The entity framework context with a User DbSet
/// > dotnet ef migrations add MyMigration
/// </summary>
public class UserContext : DbContext
{
public DbSet<User> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); var configuration = builder.Build(); string connectionString = configuration.GetConnectionString("MyConnection"); optionsBuilder.UseMySQL(connectionString);
} protected override void OnModelCreating(ModelBuilder builder)
{
// Sets the properties that make up the primary key for this entity type.
builder.Entity<User>().HasKey(m => m.ID);
base.OnModelCreating(builder);
}
}

DbContext类负责连接数据库并将User对象映射到数据库记录。数据库上下文(Database Context)可以在Startup文件中的ConfigureServices方法中用依赖注入容器进行注册的:

public void ConfigureServices(IServiceCollection services)
{
string connectionString = Configuration.GetConnectionString("MyConnection"); services.AddDbContext<UserContext>(options =>
options.UseMySQL(connectionString)
); // Add framework services.
services.AddMvc();
}

注:UseMySQLMySQL.Data.EntityFrameworkCore.Extensions里面的一个扩展方法,所以要手动添加using MySQL.Data.EntityFrameworkCore.Extensions;命名空间。这个小问题也花费了我不少的时间和精力。

namespace MySQL.Data.EntityFrameworkCore.Extensions
{
/// <summary>
/// ContextOptionsExtensions implementations for MySQL
/// </summary>
public static class MySQLDbContextOptionsExtensions
{
public static DbContextOptionsBuilder UseMySQL(this DbContextOptionsBuilder optionsBuilder,
string connectionString,
Action<MySQLDbContextOptionsBuilder> MySQLOptionsAction = null)
{
var extension = optionsBuilder.Options.FindExtension<MySQLOptionsExtension>();
if (extension == null)
extension = new MySQLOptionsExtension();
extension.ConnectionString = connectionString; IDbContextOptionsBuilderInfrastructure o = optionsBuilder as IDbContextOptionsBuilderInfrastructure;
o.AddOrUpdateExtension(extension); MySQLOptionsAction?.Invoke(new MySQLDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder;
}
}
//...
}

创建数据库

通过Migrations工具来创建数据库。

运行dotnet ef migrations add MyMigration Entity Framework .NET Core CLI Migrations命令来创建一个初始化迁移命令。

创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

运行dotnet ef database update应用一个你所创建的新的迁移到数据库。因为你的数据库还没不存在,它会在迁移被应用之前为你创建所需的数据库。

创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

然后就会在项目生成Migrations文件夹,包括20161121064725_MyMigration.cs文件、20161121064725_MyMigration.Designer.cs文件和UserContextModelSnapshot.cs文件:

创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

20161121064725_MyMigration.Designer.cs类:

[DbContext(typeof(UserContext))]
[Migration("20161121064725_MyMigration")]
partial class MyMigration
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rtm-21431"); modelBuilder.Entity("MyFirstApp.Models.User", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd(); b.Property<string>("Bio"); b.Property<string>("Email"); b.Property<string>("Name"); b.HasKey("ID"); b.ToTable("Users");
});
}
}

20161121064725_MyMigration.cs Partial类:

public partial class MyMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("MySQL:AutoIncrement", true),
Bio = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.ID);
});
} protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}

UserContextModelSnapshot类:

[DbContext(typeof(UserContext))]
partial class UserContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rtm-21431"); modelBuilder.Entity("MyFirstApp.Models.User", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd(); b.Property<string>("Bio"); b.Property<string>("Email"); b.Property<string>("Name"); b.HasKey("ID"); b.ToTable("Users");
});
}
}

新创建的数据库结构如下:

创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

将上述的Migrations文件夹中的代码与MySQL数据库表__EFMigrationsHistory对照一下,你会发现该表是用来跟踪记录实际已经应用到数据库的迁移信息。

创建User实例并将实例保存到数据库

public class Program
{
public static void Main(string[] args)
{
using (var db = new UserContext())
{
db.Users.Add(new User { Name = "Charlie Chu", Email = "charlie.thinker@aliyun.com", Bio = "I am Chalrie Chu." });
var count = db.SaveChanges(); Console.WriteLine("{0} records saved to database", count); Console.WriteLine(); Console.WriteLine("All users in database:");
foreach (var user in db.Users)
{
Console.WriteLine(" - {0}", user.Name);
}
}
}
}

参考文档

个人博客

我的个人博客