zoukankan      html  css  js  c++  java
  • Entity Framework 学习系列(3)

    写在前面


    这几天,一直都在学习Entity Framework 的Code First 开发模式。然后,一直在填坑的路上渐行渐远又因为平时工作的原因,对于EF的学习时断时续的

    今天,使用程序台应用的方式来使用EF的Code First 的开发模式。本来是想使用Web Mvc 的方式使用Code First,后来发现,在Visual Studio 2019中使用

    EF Code First连接MySQL的时候连控制器的创建不了。尝试了很多的方法,最后还是出现了如图所示的错误:

    报错

    运行所选代码生成器时出错:“值-1超出了可接受的[0,2147483647]范围。参数名称:value”

    最后,去问了度娘。大部分的人都是在说这个是Visual Studio 2019的一个Bug。然后,我又尝试了使用.Net Core Web Mvc +EF Code First 的方式创建项目

    自此就没有出现如上图所示的问题。

    一、开发环境

    • 开发工具:Visual Studio 2019

    • 开发环境:Win 10 家庭版

    • 开发数据库: MySql 8.0.17

    • ORM框架:Entity Framework 6.2.0

    二、创建项目

    【1】打开Visual Studio 2019-->创建新项目-->控制台应用

    【2】项目名称myEFCodeFirst 选择存放的位置 点击创建

    三、安装程序包

    【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数据库查看一下。如图所示:

    七、数据迁移

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

    我们该如何在不影响原有结构和有数据的情况下通过Code Frist 的方式同步更新数据库呢?

    为了完整的演示这个过程,我把原来的表以及数据删除。使用Code First 实现数据的迁移。

    【1】使用命令初始化数据并更新数据库

    • 在工具->NuGet 包管理器->程序包管理控制台 输入

    • 首先输入: Enable-Migrations

    • 我们会看到在项目中会Migrations的文件夹 如下图所示:

    • Migrations的文件夹生成Configuration配置类
    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.
            }
        }
    }
    
    

    我们把AutomaticMigrationsEnabled的属性改成true

    • 然后输入:Add-Migration Initial 初始化数据 生成Migrations的文件夹生成201908280742145_Initials初始化类 如下图:

    201908280742145_Initials初始化数据类如下:

    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");
            }
        }
    }
    
    
    • 最后输入:Update-Database 更新数据库 如下图所示:

    • 我们刷新一下数据库,就可以看到MySql数据库创建了movie

    【2】新增字段

    • 然后启动程序添加数据,并在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; }
            [Description("电影描述")]
            public string MovieDes { get; set; }
            //新增
            [Description("电影评价")]
            public string  MovieEvaluates{ get; set; }
        }
    }
    

    使用命令 更改数据库结构 add-Migration AddColunm

    生成201908280759301_AddColunm 类,记录表结构发生表化

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

    输入 update-database 如下图:

    • 最后,刷新数据库。我们就会看到在在movie表中在数据的情况下,添加了MovieEvaluates列。如下图更新前后的对比:

    【3】删除字段

    • 删除字段,亦然如此操作。

    写在最后

    至此,完成了通过Code First 方式的的使用以及实现MySql 的数据迁移。

  • 相关阅读:
    Log4NET初接触
    wwwww
    关于ASP.NET 的进程帐户对 IIS 元数据库读访问权问题
    CentOS8 .NET Core项目部署
    CentOS7.6中安装Apache及Apache常见操作和配置说明
    .net core 命令行下启动指定端口
    Centos7安装mongodb
    centos8+oracle19开机自启动
    计算机网络常用端口
    Centos7安装mongodb
  • 原文地址:https://www.cnblogs.com/ZengJiaLin/p/11422832.html
Copyright © 2011-2022 走看看