WPF+EF+Mysql(配置篇)

最近在WPF中想使用EF操作数据库Mysql。一直对数据库不是很熟练,简单记录下如何在VS2019中进行配置。

0,准备工作

安装mysql,安装vs2019....

1,在NuGet中安装库文件

其中应包括:

EntityFramework、MySql.Data和MySql.Data.Entities。在有些文章中写了是安装MySql.Data.Entity,而MySql.Data.Entity目前搜了下,已经找不到了,因此我用了MySql.Data.Entities来代替,版本号和名称如下图所示:

WPF+EF+Mysql(配置篇)_第1张图片

2,简单代码测试

2.1 XML文件



  
    
    

Xml代码如上图所示,需要注意大部分都是自动生成的,只有connectionStrings是自己添加上去的:

  
    
  

 2.2 C#代码

 使用下面的代码做简单的测试

using Link2Mysql2.Migrations;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Link2Mysql2
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {

                var blog = new Blog { Name = "cc" };
                db.Blogs.Add(blog);
                db.SaveChanges();

                // Display all Blogs from the database
                var query = from b in db.Blogs
                            orderby b.Name
                            select b;
                Blog f = db.Blogs.Find(1);
                Blog k = db.Blogs.FirstOrDefault(s => s.Name == "cc");
                f.Name = "nn";
                db.SaveChanges();
                Console.WriteLine("All blogs in the database:");
                foreach (var item in query)
                {
                    Console.WriteLine(item.Name);
                }

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }

        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
    }

    [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]

    public class BloggingContext : DbContext
    {
        public BloggingContext() : base("EFMySqlTest")
        {
            //   Database.SetInitializer(new MigrateDatabaseToLatestVersion("Link2MySQL"));
        }
        public DbSet Blogs { get; set; }


    }

}

特别注意需要加上这句话,否则会提示

找不到请求的 .Net Framework Data Provider。可能没有安装。

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]

第一次运行时会新建数据库

WPF+EF+Mysql(配置篇)_第2张图片

 运行结果如图所示

WPF+EF+Mysql(配置篇)_第3张图片

三,数据迁移

那么当修改了Blog的属性时,是会报错的

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        //public string Url { get; set; }
    }

WPF+EF+Mysql(配置篇)_第4张图片

 提示需要使用数据迁移,代码修改如下

    public class BloggingContext : DbContext
    {
        public BloggingContext() : base("EFMySqlTest")
        {
            //   Database.SetInitializer(new MigrateDatabaseToLatestVersion("Link2MySQL"));
        }
        public DbSet Blogs { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion());
            //  base.OnModelCreating(modelBuilder);
            //   modelBuilder.HasDefaultSchema("cq");
            modelBuilder.Entity().ToTable("Blogstable");
        }

    }

同时添加Configuration.cs文件,Configuration.cs文件内容如下:

namespace Link2Mysql2.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration
    {
        public Configuration()
        {
            SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
            CodeGenerator = new MySql.Data.Entity.MySqlMigrationCodeGenerator();
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
            ContextKey = "EFMySqlTest";


        }

        protected override void Seed(Link2Mysql2.BloggingContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
        }
    }
}

再次运行,不会报错,且数据库的表也会跟着修改

WPF+EF+Mysql(配置篇)_第5张图片

你可能感兴趣的:(C#)