zoukankan      html  css  js  c++  java
  • 创建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类:

    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; }
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    除了你期望的用来构建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)
        {
            builder.Entity<User>().HasKey(m => m.ID);
            base.OnModelCreating(builder);
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    OnConfiguring方法里面的指定使用MySQL provider及具体的连接字符串等逻辑也可以统一放到Startup类中的ConfigureServices方法中:

    public void ConfigureServices(IServiceCollection services)
    {
        string connectionString = Configuration.GetConnectionString("MyConnection");
    
        services.AddDbContext<UserContext>(options =>
            options.UseMySQL(connectionString)
        );
    
        // Add framework services.
        services.AddMvc();
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    注:UseMySQLMySQL.Data.EntityFrameworkCore.Extensions里面的一个扩展方法,所以要手动添加using MySQL.Data.EntityFrameworkCore.Extensions;命名空间。这个小问题也花费了我不少的时间和精力。

    创建数据库

    通过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");
                });
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    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");
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    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");
                });
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    新创建的数据库结构如下:

    将上述的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);
                }
            }
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    参考文档

    个人博客

    我的个人博客

  • 相关阅读:
    element-ui分页组件修改当前页current-page后current-change事件不触发
    使用element-ui 的table 组件 表格线条不对齐
    vue 禁止浏览器自带的后退功能
    echart 柱图的(层叠柱图和柱图)label只显示总数 ,折线图的legent上显示总数
    element-ui table组件,分别设置表头和表格内容的居中,自定义渲染
    vue-cli-3+element-ui 按需引入element-ui的配置
    今天使用ElementUI与vue-quill-editor的时候发现,富文本编辑框选项对齐出现了点问题。
    vue-router 切换页面的时候,页面没有请求,
    msvcp140.dll缺失解决办法
    CTF中RSA题目的pem文件处理
  • 原文地址:https://www.cnblogs.com/moonvan/p/6246533.html
Copyright © 2011-2022 走看看