在EF中使用MySQL的方法及常見問題_MySQL

有時需要在網上租用空間或數據庫,Mysql成本低一些,所以想將sql server轉成mysql……

注意:在安裝Mysql時要選擇文字集為utf8,否則將不能使用中文(當前也可以在創建數據庫時使用utf8,不過我不知道在ef生成數據庫時如何設置,希望高手指點)

一、在項目中引用mysql的EF包

通過NuGet包管理器安裝:EntityFramework6.1.3、MySql.Data.Entity6.9.8

也可以用nuget的命令行加入:

Install-Package MySql.Data.Entity

二、新建相關類

1、新建 User 實體類

并定義實例的字段長度,不定義的話會出現Specified key was too long;max key length is 767 bytes 的錯誤,這是因為string 類型直接映射到mysql 中的話是longtext,而mysql 支持最大長度為767 bytes.

 public class User { public int Id { get; set; } [StringLength(30)] public string UserName { get; set; } [MaxLength(30)] public string PassWord { get; set; } } 

2、新建 MyContext 類

并說明用mysql進行實現 [dbconfigurationtype(typeof(mysqlefconfiguration))]

 [DbConfigurationType(typeof(MySqlEFConfiguration))] public class MyContext : DbContext { public MyContext() : base("name=MyContext")//web.config中connectionstring的名字 { } public DbSet<user> Users { get; set; } }</user>

3、寫測試代碼

 Database.SetInitializer(new DropCreateDatabaseIfModelChanges<mycontext>()); var context = new MyContext(); //插入一行值 context.Users.Add(new User { UserName = "EF6MySQL" }); context.SaveChanges(); </mycontext>

三、配置Web.config

中加入以下代碼:

 <add name="MyContext" connectionstring="Data Source=localhost;port=3306;Initial Catalog=MySQL_EF;user id=root;password=root;" providername="MySql.Data.MySqlClient"></add>

完整的web.config如下:

  <configuration><configsections><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/&#63;LinkID=237468 --><section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirepermission="false"></section></configsections><entityframework><defaultconnectionfactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory , EntityFramework"></defaultconnectionfactory><providers><provider invariantname="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"></provider><provider invariantname="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers></entityframework><system.data><dbproviderfactories><remove invariant="MySql.Data.MySqlClient"></remove><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.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></add></dbproviderfactories></system.data><connectionstrings><add name="MyContext" connectionstring="Data Source=localhost;port=3306;Initial Catalog=MySQL_EF;user id=root;password=root;" providername="MySql.Data.MySqlClient"></add></connectionstrings></configuration>

最后,運行程序,完成數據庫自動創建

常見問題

?出現錯誤提示: Specified key was too long;max key length is 767 bytes

1)查看實體的字符串類型屬性是否設置了長度

2)MyContext 類中是否聲明為生成為mysql 數據類型的 [DbConfigurationType(typeof(MySqlEFConfiguration))]

?出現錯誤提示: Model compatibility cannot be checked because the database does not contain model metadata

刪除已生成的數據庫后重新運行程序

?出現錯誤提示:序列不包含任何匹配元素

檢查一下:

例如:1.

 public class Employee { [Key] public int EmployeeId { get; set; } public string Name { get; set; } [ForeignKey("ManagerId")] public Employee Manager { get; set; } public int ManagerId { get; set; } }[ForeignKey("ManagerId")] public Employee Manager { get; set; } public int ManagerId { get; set; }這個外鍵設置。 

2.[Column(TypeName=”VARCHAR(254)”)] public string ColumnName { get; set; } 這樣的定義,改成: [MaxLength(254)] [Column(TypeName=”VARCHAR”)] public string ColumnName { get; set; }3.(以下代碼未測試,因為我不是這樣用的,在下篇文章中將進行測試)

 modelBuilder.Entity<category>() .HasKey(c =&gt; c.IdCategory ) .HasOptional(p =&gt; p.Children) .WithMany() .HasForeignKey(c =&gt; c.ChildrenId);</category>

改成:

 modelBuilder.Entity<category>() .HasKey(c =&gt; c.IdCategory ) .HasMany(p =&gt; p.Children) .WithOptional() .HasForeignKey(c =&gt; c.ChildrenId);</category>

.WithMany()換成.WithOptional()

以上所述是小編給大家介紹的在EF中使用MySQL的方法及常見問題的全部敘述,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!

? 版權聲明
THE END
喜歡就支持一下吧
點贊11 分享