EntityFramework+MySql数据库(code first方式)

(学习大佬tkbSimplest的CodeFirst开发系列)

一、安装MySQL 8.0.13

  1. 系统WIN7 SP1
  2. 在MySQL官网下载mysql-installer-community-8.0.13.0.msi
  3. MySQL for Visual Studio 1.2.8版本安装失败回滚,只安装1.0.2版本

    二、Visual Studio

  4. 已有VS2010
  5. MySQL.Data依赖Google.Protobuf,Google.Protobuf依赖.Net 4.5以上,VS2010 不支持.Net 4.5,重新安装VS2015
  6. 从NuGet安装两个包:MySql.Data和MySql.Data.Entity
  7. 新建Donator、Context类:
public class Donator
    {
        public int DonatorId { get; set; }
        public string Name { get; set; }
        public decimal Amount { get; set; }
        public DateTime DonateDate { get; set; }
    }
    
     [DbConfigurationType(typeof(MySql.Data.EntityFramework.MySqlEFConfiguration))]
    public class Context : DbContext
    {
        public Context()
            : base("name=CodeFirst")
        ///调用了父类的构造函数,并且传入了一个键值对,键是name,值是CodeFirst,这个键值对是定义在应用程序的配置文件中的
        {
        }
        public DbSet<Donator> Donators { get; set; }
    }
  1. 测试:
class Program
    {
        static void Main(string[] args)
        {
            using (var context = new Context())
            {
                context.Database.CreateIfNotExists();//如果数据库不存在时则创建
                context.Donators.Add(
                    new Donator
                    {
                        DonatorId = 1,
                        Name = "Niu",
                        Amount = 50,
                        DonateDate = DateTime.Now
                    });
                context.SaveChanges();
            }
            Console.Write("DB has Created!");//提示DB创建成功
            Console.Read();
        }
  1. App.config添加:
<connectionStrings>
    <add name="CodeFirst" connectionString="Data Source=localhost;port=3306;Initial Catalog=CodeFirst;user id=root;password=root;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>

运行:

'MySql.Data.Entity.EFMySqlCommand.set_DbConnection(System.Data.Common.DbConnection)' to access method 'MySql.Data.MySqlClient.MySqlConnection.get_Settings()' failed."

呃。。。百度半天各种修改,卒。Google一下

Oracle renamed the package to MySql.Data.EntityFramework for v8.x. You need to uninstall MySql.Data.Entity and install MySql.Data.EntityFramework.
  1. NuGet卸载MySql.Data.Entity,安装MySql.Data.EntityFramework
  2. 运行:

附:

打开MySQL 8.0 Command Line Client,命令:
1. use mysql;
2. alter user 'root'@'localhost' identified with mysql_native_password by '自个的密码';
3. flush privileges;

猜你喜欢

转载自www.cnblogs.com/SurroundSea/p/9897085.html
今日推荐