首页 > 代码库 > 创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表
创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表
创建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; } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
除了你期望的用来构建Movie模型的属性外,将作为数据库主键的ID
字段是必须的。
安装Entity Framework Core 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) { builder.Entity<User>().HasKey(m => m.ID); base.OnModelCreating(builder); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
OnConfiguring
方法里面的指定使用MySQL provider及具体的连接字符串等逻辑也可以统一放到Startup类中的ConfigureServices
方法中:
public void ConfigureServices(IServiceCollection services){ string connectionString = Configuration.GetConnectionString("MyConnection"); services.AddDbContext<UserContext>(options => options.UseMySQL(connectionString) ); // Add framework services. services.AddMvc();}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
注:UseMySQL
是MySQL.Data.EntityFrameworkCore.Extensions
里面的一个扩展方法,所以要手动添加using MySQL.Data.EntityFrameworkCore.Extensions;
命名空间。这个小问题也花费了我不少的时间和精力。
创建数据库
通过Migrations工具来创建数据库。
运行dotnet ef migrations add MyMigration
Entity Framework .NET Core CLI Migrations命令来创建一个初始化迁移命令。
运行dotnet ef database update
应用一个你所创建的新的迁移到数据库。因为你的数据库还没不存在,它会在迁移被应用之前为你创建所需的数据库。
然后就会在项目生成Migrations文件夹,包括20161121064725_MyMigration.cs文件、20161121064725_MyMigration.Designer.cs文件和UserContextModelSnapshot.cs文件:
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"); }); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
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"); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
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"); }); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
新创建的数据库结构如下:
将上述的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); } } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
参考文档
- HowTo: Starting with MySQL EF Core provider and Connector/Net 7.0.4
- .NET Core - New Database
- ASP.NET CORE 1.0 WITH MYSQL AND ENTITY FRAMEWORK CORE
- ASP.NET CORE 1.0 WITH SQLITE AND ENTITY FRAMEWORK 7
个人博客
我的个人博客
创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表