Entity Framework Learning Series (3) - MySql Code First development mode + Data Migration

EDITORIAL


These days, always studying Entity Framework Code First development model of. Then, fill the pit road has been lopsided - but also because of the usual work for EF learning intermittent ~

Today, using the program to use table mode of application development model of the EF Code First. Wanted to use the Web Mvc way to use Code First, it was discovered that in use in Visual Studio 2019

EF Code First time connection of MySQL can not even create a controller. I tried a lot of ways, but finally there was an error as shown:

Error
Error code generator selected run: "exceeds the acceptable value of -1 [0,2147483647] Range Parameter Name:. Value"

Finally, ask the degree of your mother. Most of the people are saying this is a Bug Visual Studio 2019's. Then, I tried to create a project using .Net Core Web Mvc + EF Code First way

Since the problem is shown above will not occur.

First, the development environment


  • Development tools: Visual Studio 2019

  • Development Environment: Win 10 Home Edition

  • Development of the database: MySql 8.0.17

  • ORM framework: Entity Framework 6.2.0

Second, create a project


[1] Open Visual Studio 2019 -> Create a new project -> Console Application

[2] project name myEFCodeFirst position selection, click Create storage

Third, the installation package

【1】项目->NuGet包管理->管理解决方案的NuGet 程序包->浏览->搜索Entity Framework 安装 EntityFramework 6.2.0勾选项目 点击安装

【2】在浏览->搜索MySql.Data 安装MySql.Data 6.10.9版本

【3】浏览->搜索MySql.Data.Entity 安装MySql.Data.Entity 6.10.9 版本

【4】打开引用,查看引用。如下图所示的引用表示安装成功。

四、创建模型

【1】创建Movie

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace myEFCodeFirst_03
{
    public class movie
    {
        [Description("主键")]
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        [Description("电影名称")]
        public string Title { get; set; }
        [Description("日期")]
        public DateTime ReleaseDate { get; set; }
        [Description("类型")]
        public string Genre { get; set; }
        [Description("价格")]
        public decimal Price { get; set; }
    }
}

【2】创建DatabaseContext上下文

  • 需要引用** using System.Data.Entity**
using System.Data.Entity;

namespace myEFCodeFirst_03
{
    //
    [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
    public class DataBaseContext:DbContext
    {
        public DataBaseContext() : base("name=myCodeFirstConn") { }
        public DbSet<movie> movies { get; set; }
    }
}

五、连接字符串


  • 打开App.config 创建 ConnectionStrings
<connectionStrings>
<add name="myCodeFirstConn" connectionString="Data Source=localhost;user id=root;Password=root;database=myCodeFirstDb;port=3306;"providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
        <parameter value="mssqllocaldb" />
    </parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</providers>
</entityFramework>

六、编辑程序


  • Program声明上下文实例
using System;
using System.Collections.Generic;

namespace myEFCodeFirst_03
{
    class Program
    {
        static void Main(string[] args)
        {
            //声明上下文依赖
            DataBaseContext _db = new DataBaseContext();
            //声明movie类
            List<movie> lstmovie = new List<movie> {
                new movie{ Title="速度与激情系列1",Genre="动作",ReleaseDate=DateTime.Now,Price=50 },
                new movie{ Title="速度与激情系列2",Genre="动作",ReleaseDate=DateTime.Now,Price=50 },
                new movie{ Title="速度与激情系列3",Genre="动作",ReleaseDate=DateTime.Now,Price=50 },
                new movie{ Title="速度与激情系列4",Genre="动作",ReleaseDate=DateTime.Now,Price=50 },
                new movie{ Title="速度与激情系列5",Genre="动作",ReleaseDate=DateTime.Now,Price=50 },
                new movie{ Title="速度与激情系列6",Genre="动作",ReleaseDate=DateTime.Now,Price=50 },
                new movie{ Title="速度与激情系列7",Genre="动作",ReleaseDate=DateTime.Now,Price=50 },
                new movie{ Title="速度与激情系列8",Genre="动作",ReleaseDate=DateTime.Now,Price=50 },
            };
            _db.movies.AddRange(lstmovie);
            if (_db.SaveChanges() > 0) { Console.WriteLine("添加成功"); Console.ReadKey(); }
            else { Console.WriteLine("添加失败");Console.ReadKey();  }
            
        }
    }
}

运行项目,程序台显示添加成功代表数据已经成功添加到数据库。如图所示:

我们到MySQL数据库查看一下。如图所示:

七、数据迁移


我们在开发的过程中常常会遇到表结构发生了变化,比如要在原来的表结构上新增或者删除一个字段。

Database synchronization update it without us how without affecting the original structure and data through the Code Frist way?

For a complete demonstration of this process, I put the original tables and data deletion. Use Code First realize data migration.

[1] using the command to initialize the data and update the database

  • Package Manager console input> - in Tools -> NuGet Package Manager

  • First, enter: Enable-Migrations
  • We will see in the project will Migrations folder as shown below:

  • In Migrations clip files generated Configuration configuration class
namespace myEFCodeFirst_03.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<myEFCodeFirst_03.DataBaseContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }
        protected override void Seed(myEFCodeFirst_03.DataBaseContext context)
        {
            //  This method will be called after migrating to the latest version.
            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.
        }
    }
}

We AutomaticMigrationsEnabled properties into true

  • Then enter: Add-Migration Initialinitialization data generated Migrations folder generated 201908280742145_Initials initialize the class as shown below:

201908280742145_Initials initialization data classes are as follows:

namespace myEFCodeFirst_03.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class Initials : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.movie",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        Title = c.String(unicode: false),
                        ReleaseDate = c.DateTime(nullable: false, precision: 0),
                        Genre = c.String(unicode: false),
                        Price = c.Decimal(nullable: false, precision: 18, scale: 2),
                        MovieDes = c.String(unicode: false),
                    })
                .PrimaryKey(t => t.Id);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.movie");
        }
    }
}
  • Last Input: Update-Databaseupdating the database as shown below:

  • We refresh the database, you can see the MySql database to create a movie class

[2] New field

  • Then add data to start the program, and Movie add movies evaluation class field
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace myEFCodeFirst_03
{
    public class movie
    {
        [Description("主键")]
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        [Description("电影名称")]
        public string Title { get; set; }
        [Description("日期")]
        public DateTime ReleaseDate { get; set; }
        [Description("类型")]
        public string Genre { get; set; }
        [Description("价格")]
        public decimal Price { get; set; }
        [Description("电影描述")]
        public string MovieDes { get; set; }
        //新增
        [Description("电影评价")]
        public string  MovieEvaluates{ get; set; }
    }
}
  • Use the command to change the database structure add-Migration AddColunm

  • Generating 201908280759301_AddColunm type, the recording of the table structure of Table

namespace myEFCodeFirst_03.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class AddColunm : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.movie", "MovieEvaluates", c => c.String(unicode: false));
        }
        
        public override void Down()
        {
            DropColumn("dbo.movie", "MovieEvaluates");
        }
    }
}
  • Input update-databasefollows:

  • Finally, refresh the database. We will see in the movie in the table in the case of the data, add a MovieEvaluates columns. FIG comparison before and after update as follows:

[3] Delete field

  • Delete fields, so the operation is no different.

Written in the last


This completes by using the Code First approach and the achievement of MySql data migration.

Guess you like

Origin www.cnblogs.com/ZengJiaLin/p/11422832.html
Recommended