在Models文件夹下添加一个User类:php
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
字段是必须的。mysql
注:其中"MySql.Data.EntityFrameworkCore": "7.0.6-ir31",
要7.0.6以上版本。
Missing implementation for running EntityFramework Core code first migration。sql
在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
方法中用依赖注入容器进行注册的:json
public void ConfigureServices(IServiceCollection services) { string connectionString = Configuration.GetConnectionString("MyConnection"); services.AddDbContext<UserContext>(options => options.UseMySQL(connectionString) ); // Add framework services. services.AddMvc(); }
注:UseMySQL
是MySQL.Data.EntityFrameworkCore.Extensions
里面的一个扩展方法,因此要手动添加using MySQL.Data.EntityFrameworkCore.Extensions;
命名空间。这个小问题也花费了我很多的时间和精力。mvc
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工具来建立数据库。app
运行dotnet ef migrations add MyMigration
Entity Framework .NET Core CLI Migrations命令来建立一个初始化迁移命令。asp.net
运行dotnet ef database update
应用一个你所建立的新的迁移到数据库。由于你的数据库还没不存在,它会在迁移被应用以前为你建立所需的数据库。ide
而后就会在项目生成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"); }); } }
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"); }); } }
新建立的数据库结构以下:
将上述的Migrations文件夹中的代码与MySQL数据库表__EFMigrationsHistory
对照一下,你会发现该表是用来跟踪记录实际已经应用到数据库的迁移信息。
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); } } } }