創(chuàng)建ASP.NET Core MVC應(yīng)用程序(3)-?基于Entity Framework Core(Code First)創(chuàng)建MySQL數(shù)據(jù)庫表
創(chuàng)建數(shù)據(jù)模型類(POCO類)
在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; }
}
}
除了你期望的用來構(gòu)建Movie模型的屬性外再愈,將作為數(shù)據(jù)庫主鍵的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ù)庫上下文
在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è)小問題也花費(fèi)了我不少的時(shí)間和精力。
創(chuàng)建數(shù)據(jù)庫
通過Migrations工具來創(chuàng)建數(shù)據(jù)庫析孽。
運(yùn)行dotnet ef migrations add MyMigration
Entity Framework .NET Core CLI Migrations命令來創(chuàng)建一個(gè)初始化遷移命令搭伤。
運(yùn)行dotnet ef database update
應(yīng)用一個(gè)你所創(chuàng)建的新的遷移到數(shù)據(jù)庫。因?yàn)槟愕臄?shù)據(jù)庫還沒不存在袜瞬,它會(huì)在遷移?被應(yīng)用之前為你創(chuàng)建所需的數(shù)據(jù)庫怜俐。
然后就會(huì)在項(xiàng)目生成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");
});
}
}
新創(chuàng)建的數(shù)據(jù)庫結(jié)構(gòu)如下:
將上述的Migrations文件夾中的代碼與MySQL數(shù)據(jù)庫表__EFMigrationsHistory
對照一下邓尤,你會(huì)發(fā)現(xiàn)該表是用來跟蹤記錄實(shí)際已經(jīng)應(yīng)用到數(shù)據(jù)庫的遷移信息拍鲤。
創(chuàng)建User實(shí)例并將實(shí)例保存到數(shù)據(jù)庫
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);
}
}
}
}
參考文檔
- 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