建立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類: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

安裝Entity Framework Core MySQL相關依賴項

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

建立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方法中用依賴注入容器進行註冊的:json

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;命名空間。這個小問題也花費了我很多的時間和精力。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對照一下,你會發現該表是用來跟蹤記錄實際已經應用到數據庫的遷移信息。

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

參考文檔

我的博客

個人我的博客

相關文章
相關標籤/搜索