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来代替,版本号和名称如下图所示:

2,简单代码测试

2.1 XML文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="EFMySqlTest" connectionString="Data Source=localhost;port=3306;Initial Catalog=cccc;User id=root;password=123456;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.10.9.0" newVersion="6.10.9.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

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

  <connectionStrings>
    <add name="EFMySqlTest" connectionString="Data Source=localhost;port=3306;Initial Catalog=cccc;User id=root;password=123456;" providerName="MySql.Data.MySqlClient" />
  </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<BloggingContext, Configuration>("Link2MySQL"));
        }
        public DbSet<Blog> Blogs { get; set; }


    }

}

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

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

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

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

 运行结果如图所示

三,数据迁移

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

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

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

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

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<BloggingContext, Configuration>());
            //  base.OnModelCreating(modelBuilder);
            //   modelBuilder.HasDefaultSchema("cq");
            modelBuilder.Entity<Blog>().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<Link2Mysql2.BloggingContext>
    {
        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<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
        }
    }
}

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

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值