最近在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.
}
}
}
再次运行,不会报错,且数据库的表也会跟着修改