在EF中使用MySQL的方法及常见问题
作者:xiaof2000 时间:2024-01-28 11:22:03
有时需要在网上租用空间或数据库,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; }
}
3、写测试代码
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
var context = new MyContext();
//插入一行值
context.Users.Add(new User { UserName = "EF6MySQL" });
context.SaveChanges();
三、配置Web.config
在<connectionStrings>中加入以下代码:
<add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=MySQL_EF;user id=root;password=root;" providerName="MySql.Data.MySqlClient" />
完整的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>
最后,运行程序,完成数据库自动创建
常见问题
•出现错误提示: 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 => 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()
以上所述是小编给大家介绍的在EF中使用MySQL的方法及常见问题的全部叙述网站的支持!
来源:http://www.cnblogs.com/xiaof2000/archive/2016/06/27/efmysql.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用python获取邮箱邮件的设置方法
python 配置uwsgi 启动Django框架的详细教程
python assert断言的实例用法
SQLServer 2008 新增T-SQL 简写语法
rollup打包vue组件并发布到npm的方法
![](https://img.aspxhome.com/file/2023/1/123211_0s.png)
django框架事务处理小结【ORM 事务及raw sql,customize sql 事务处理】
SQL语句检测sp4补丁是否安装
基于Vue的侧边目录组件的实现
![](https://img.aspxhome.com/file/2023/8/123208_0s.gif)
Python数据清洗&预处理入门教程
![](https://img.aspxhome.com/file/2023/0/114640_0s.png)
Python字典深浅拷贝与循环方式方法详解
![](https://img.aspxhome.com/file/2023/7/71317_0s.png)
javascript设计模式 – 简单工厂模式原理与应用实例分析
PHP PDOStatement::fetchAll讲解
python_tkinter事件类型详情
![](https://img.aspxhome.com/file/2023/2/133662_0s.png)
Python3简单实例计算同花的概率代码
![](https://img.aspxhome.com/file/2023/6/70746_0s.png)
pandas 数据索引与选取的实现方法
sql2000如何完美压缩.mdf文件
MySQL6.0新增特性
javascript设计模式 – 单例模式原理与应用实例分析
JavaScript实现图片自动加载的瀑布流效果
![](https://img.aspxhome.com/file/2023/3/123373_0s.jpg)
关于PyQt5主窗口图标显示问题汇总
![](https://img.aspxhome.com/file/2023/9/85029_0s.png)