前面有篇文章,尝试了db first方式,但不知道是什么原因一直没有成功,到最后也没解决,今天就尝试下code first的方式。
[EF]vs15+ef6+mysql这个问题,你遇到过么?
在上面的步骤完成后,修改web.config文件,内容如下:
<?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.5.2" /> </startup> <entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6"> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> </providers> </entityFramework> <system.data> <DbProviderFactories> <remove invariant="MySql.Data.MySqlClient" /> <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> </DbProviderFactories> </system.data> <connectionStrings> <add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=myshop;user id=sa;password=sa;" providerName="MySql.Data.MySqlClient"/> </connectionStrings> </configuration>
注意entityFramework 节点,默认是不会有codeConfigurationType属性的,请添加。否则会出现下面的错误:Specified key was too long; max key length is 767 bytes
测试
实体类
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wolfy.Ef_MySql_CodeFirst { public class Product { public int Id { set; get; } [MaxLength(128)] public string Name { set; get; } [MaxLength(128)] public string Category { set; get; } public decimal Price { set; get; } public DateTime CreateDate { set; get; } } }
插入信息
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wolfy.Ef_MySql_CodeFirst { class Program { static void Main(string[] args) { var dbContext = new MyContext(); IDatabaseInitializer<MyContext> dbInitializer = null; if (dbContext.Database.Exists()) { //如果数据库已经存在 dbInitializer = new DropCreateDatabaseIfModelChanges<MyContext>(); } else { //总是先删除然后再创建 dbInitializer = new DropCreateDatabaseAlways<MyContext>(); } //Database.SetInitializer(dbInitializer);
dbInitializer.InitializeDatabase(dbContext); dbContext.Products.Add(new Product() { CreateDate = DateTime.Now.AddDays(1), Name = "南孚电池", Category = "生活用品", Price = 3 }); dbContext.SaveChanges(); } } }
还有一个错误经常出现
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
大概意思是:不能检查模型的兼容性,因为数据库不包含模型元数据。在使用code first或者code fisrt迁移进行数据库创建的时候需要检查模型的兼容性。
此时,虽然生成了表_migrationhistory,但是该表内容为空。
这个时候可以将数据库删除,重新生成就可以解决。
其中表_migrationhistory为创建历史表。
Products表
发现添加的数据中中文为乱码,这是因为mysql默认的字符集为latin
关于乱码的解决方案很多,你可以修改数据库的字符集,或者数据表的字符集。也可以这样,修改连接字符串:
<connectionStrings> <add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=myshop;user id=sa;password=sa;charset=utf8" providerName="MySql.Data.MySqlClient"/> </connectionStrings>
折腾了一上午,一个简单的demo出来了。