标签:
有时需要在网上租用空间或数据库,Mysql成本低一些,所以想将sql server转成mysql……
一、在项目中引用mysql的EF包
Install-Package MySql.Data.Entity
完整的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> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory , EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> <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" /> <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" /> </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" /> </connectionStrings> </configuration>
例如: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 => c.IdCategory ) .HasOptional(p => p.Children) .WithMany() .HasForeignKey(c => c.ChildrenId); 改成: modelBuilder.Entity<Category>() .HasKey(c => c.IdCategory ) .HasMany(p => p.Children) .WithOptional() .HasForeignKey(c => c.ChildrenId); .WithMany()换成.WithOptional()
标签:
原文地址:http://www.cnblogs.com/xiaof2000/p/efmysql.html