创建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; }
}
}

除了你期望的用来构建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)
{
// 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方法中用依赖注入容器进行注册的:

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;命名空间。这个小问题也花费了我不少的时间和精力。

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工具来创建数据库。

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

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

参考文档

个人博客

我的个人博客

创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表的更多相关文章

  1. 在Apworks数据服务中使用基于Entity Framework Core的仓储(Repository)实现

    <在ASP.NET Core中使用Apworks快速开发数据服务>一文中,我介绍了如何使用Apworks框架的数据服务来快速构建用于查询和管理数据模型的RESTful API,通过该文的介 ...

  2. 在Entity Framework 中用 Code First 创建新的数据库

    在Entity Framework 中用 Code First 创建新的数据库 (原文链接) 本文将逐步介绍怎样用Code First 创建新数据库,使用在代码中定义类和API中提供的特性(Attri ...

  3. ASP.Net Core项目在Mac上使用Entity Framework Core 2.0进行迁移可能会遇到的一个问题.

    在ASP.Net Core 2.0的项目里, 我使用Entity Framework Core 2.0 作为ORM. 有人习惯把数据库的连接字符串写在appSettings.json里面, 有的习惯写 ...

  4. .NET Core学习笔记(8)——Entity Framework Core之Database First

    曾经我以为再也不会去弄啥Database First,然鹅我错了.这个世界上就是有啪啪打脸和真香的时候.当小伙伴拿着做好的DB表结构和SQL脚本递过来的时候,我知道我没法拒绝.望着他突起的肱二头肌和充 ...

  5. ASP.NET Core 快速入门(Razor Pages + Entity Framework Core)

    引子 自从 2009 年开始在博客园写文章,这是目前我写的最长的一篇文章了. 前前后后,我总共花了 5 天的时间,每天超过 3 小时不间断写作和代码调试.总共有 8 篇文章,每篇 5~6 个小结,总截 ...

  6. ASP.NET CORE系列【二】使用Entity Framework Core进行增删改查

    介绍 EntityFrameworkCore EF core 是一个轻量级的,可扩展的EF的跨平台版本.对于EF而言 EF core 包含许多提升和新特性,同时 EF core 是一个全新的代码库,并 ...

  7. ASP.NET CORE系列【三】使用Entity Framework Core进行增删改查

    身份验证 以前我们熟悉的web.config中配置的form验证,现在没有了.我们来看看在Core里面如何配置: 首先需要NuGet安装一个包:Microsoft.AspNetCore.Authent ...

  8. .NET Core学习笔记(9)——Entity Framework Core之Code First

    上篇我们介绍了怎么通过已有的SQLServer表来创建实体类,本篇我们改用Code First的方式,由C#代码书写的实体类来生成SQLServer表.并且通过简单的Console APP往SQLSe ...

  9. Entity Framework 6 Code First创建

    基本上我是DB先设计好的,所以就按现存在的table去写程式. 1.Web.config里配置Db连接字串,Connection String Name为DefaultConnection <c ...

随机推荐

  1. java 遍历arrayList的四种方法

    package com.test; import java.util.ArrayList;import java.util.Iterator;import java.util.List; public ...

  2. [nRF51822] 11、基础实验代码解析大全 · 实验16 - 内部FLASH读写

     一.实验内容: 通过串口发送单个字符到NRF51822,NRF51822 接收到字符后将其写入到FLASH 的最后一页,之后将其读出并通过串口打印出数据. 二.nRF51822芯片内部flash知识 ...

  3. 30个你必须记住的CSS选择符

    所以你学会了基础的id,类和后代选择符,然后你就一直用它们了吗?如果是这样,你丢失了(css的)巨大的灵活性.在本文中提到的很多选择器属于CSS3规范的一部分,因此,只有在现代浏览器中才可使用. 1. ...

  4. jdk1.7.0_80源码包结构

    解压源码src.zip,jdk源码结构如下所示: src |--com.sun    sun公司对jdk的实现,Oracle官方不支持,不保证跨平台(可能一些类linux有而windows没有),甚至 ...

  5. C#设计模式系列:享元模式(Flyweight)

    当频繁地从数据源读取数据时,读出的内容存在重复,那么需要使用享元模式(Flyweight)来提高内存效率,Flyweight模式将节省更多空间,共享的Flyweight越多,空间节省越大. 1.享元模 ...

  6. ExtJs4常用配置方法备忘

    viewport布局常用属性 new Ext.Viewport({ layout: "border", renderTo: Ext.getBody(), defaults: { b ...

  7. 【Win 10应用开发】认识一下UAP项目

    Windows 10 SDK预览版需要10030以上版本号的Win 10预览版系统才能使用.之前我安装的9926的系统,然后安装VS 2015 CTP 6,再装Win 10 SDK,但是在新建项目后, ...

  8. 传智播客--XAML布局--连连看界面(小白内容)

    一个简单的10*10连连看,有100个格子,可以在XAML里面用ColumnDefinition和RowDefinition各写10组,但是这样效率会很慢,因此,可以采用动态生成的方式进行. publ ...

  9. 分享一个LiteDB做的简单考试系统辅助工具

    凌晨,被安排在公司值班,因为台风“灿鸿”即将登陆,风力太大,办公楼,车间等重要部分需要关注.所以无聊,那就分享一下,今天给朋友临时做的一个小的考试系统辅助工具吧.其实非常小,需求也很简单,但是可以根据 ...

  10. Util应用程序框架公共操作类(七):Lambda表达式公共操作类

    前一篇扩展了两个常用验证方法,本文将封装两个Lambda表达式操作,用来为下一篇的查询扩展服务. Lambda表达式是一种简洁的匿名函数语法,可以用它将方法作为委托参数传递.在Linq中,大量使用La ...