MySQL CodeFirst的配置与注意事项

mysql+ef的配置相比较mssql+ef来说复杂一些。我的感受就是配置难度在于插件版本造成的各种不兼容问题。另外参考了很多博客,将多个博客里的经验综合才得以实现,因为不是每个人的操作都和那些博客作者描述的情况一致,不过解决之后其他都好说。现在从零开始操作mysql+CodeFirst的实现,总结我的配置过程。先确保安装并打开了mysql数据库:

1.新建控制台项目

2.在程序包管理器控制台里依次安装(注意:EF版本一定要低,另外第②和第③保证版本一致,因为③和②有依赖关系,版本不一致会导致一些问题)
①Install-Package EntityFramework -Version 6.1.3

②Install-Package MySql.Data -Version 6.8.8

③Install-Package MySql.Data.Entity -Version 6.8.8

3.App.Config配置文件里添加:

<connectionStrings>
<add name="connStr" connectionString="data source=127.0.0.1;user 
id=root;password=123456;database=sqltest;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>

4.依次新建Person实体类,PersonConfig类,详细代码:

public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

 

class PersonConfig : EntityTypeConfiguration<Person>
    {
        public PersonConfig()
        {
            this.ToTable("T_Persons");
        }
    }

5.新建MyContext类,详细代码(注意:如果不在类上方做DBConfigurationType标记的话会在最终操作update-database时出错,别忘记)

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
    class MyContext : DbContext
    {
        public MyContext()
            : base("name=connStr")//name对应配置文件里的连接字符串name属性
        {

        }
        public DbSet<Person> Persons { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());
        }
    }

6.继续在程序包管理器控制台运行命令Enable-Migrations -force,成功后将会出现如图所示信息:

注意:此时在项目下会自动生成文件夹和一个类,如图所示:

7.打开Configuration.cs,将AutomaticMigrationsEnabled的值修改为true,并且在程序包管理器控制台运行命令update-database -force,成功后将会出现如图所示信息:

注意:没在MyContext类上方标记DBConfigurationType害得我这一步浪费了好几个小时,会提示No MigrationSqlGenerator found for provider 'MySql.Data.MySqlClient'. Use the SetSqlGenerator method in the target migrations configuration class to register additional SQL generators.

8.现在来测试效果。目前mysql里没有名字叫sqltest的数据库存在,CodeFirst是通过代码来自动生成数据库的。主函数代码如下:

using (MyContext ctx = new MyContext())
            {
                Person per1 = new Person { Name = "per1", Age = 12 };
                Person per2 = new Person { Name = "per2", Age = 17 };
                Person per3 = new Person { Name = "per3", Age = 19 };
                ctx.Persons.Add(per1);
                ctx.Persons.Add(per2);
                ctx.Persons.Add(per3);
                ctx.SaveChanges();
                Console.WriteLine("添加成功");
            }
            Console.ReadKey();

9.运行后如果成功,刷新Navicat for MySQL的数据库列表可以发现新生成的数据库:

注意:①自动生成了__migrationhistory表说明配置很成功。②PersonConfig.cs里的this.ToTable("T_Persons");影响实体类映射成功后的表名。③默认Id字段为主键并且自增,因此不需要手动为Id属性赋值。

 

posted @ 2018-01-11 17:22  天堂画家  阅读(1001)  评论(0编辑  收藏  举报