Models文件夾下添加一個(gè)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; }
    }
}

除了你期望的用來(lái)構(gòu)建Movie模型的屬性外,將作為數(shù)據(jù)庫(kù)主鍵的ID字段是必須的。

安裝Entity Framework Core MySQL相關(guān)依賴項(xiàng)

注:其中"MySql.Data.EntityFrameworkCore": "7.0.6-ir31",要7.0.6以上版本。
Missing implementation for running EntityFramework Core code first migration

創(chuàng)建Entity Framework Context數(shù)據(jù)庫(kù)上下文

Models文件夾下添加一個(gè)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);
    }
}

OnConfiguring方法里面的指定使用MySQL provider及具體的連接字符串等邏輯也可以統(tǒng)一放到Startup類中的ConfigureServices方法中:

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里面的一個(gè)擴(kuò)展方法,所以要手動(dòng)添加using MySQL.Data.EntityFrameworkCore.Extensions;命名空間。這個(gè)小問(wèn)題也花費(fèi)了我不少的時(shí)間和精力。

創(chuàng)建數(shù)據(jù)庫(kù)

通過(guò)Migrations工具來(lái)創(chuàng)建數(shù)據(jù)庫(kù)。

運(yùn)行dotnet ef migrations add MyMigration Entity Framework .NET Core CLI Migrations命令來(lái)創(chuàng)建一個(gè)初始化遷移命令。

運(yùn)行dotnet ef database update應(yīng)用一個(gè)你所創(chuàng)建的新的遷移到數(shù)據(jù)庫(kù)。因?yàn)槟愕臄?shù)據(jù)庫(kù)還沒(méi)不存在,它會(huì)在遷移被應(yīng)用之前為你創(chuàng)建所需的數(shù)據(jù)庫(kù)。

然后就會(huì)在項(xiàng)目生成Migrations文件夾,包括20161121064725_MyMigration.cs、20161121064725_MyMigration.Designer、UserContextModelSnapshot這樣的文件:

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");
            });
    }
}

新創(chuàng)建的數(shù)據(jù)庫(kù)結(jié)構(gòu)如下:

將上述的Migrations文件夾中的代碼與MySQL數(shù)據(jù)庫(kù)表__EFMigrationsHistory對(duì)照一下,你會(huì)發(fā)現(xiàn)該表是用來(lái)跟蹤記錄實(shí)際已經(jīng)應(yīng)用到數(shù)據(jù)庫(kù)的遷移信息。

創(chuàng)建User實(shí)例并將實(shí)例保存到數(shù)據(jù)庫(kù)

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);
            }
        }
    }
}

參考文檔