有时需要在网上租用空间或数据库,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的方法及常见问题的更多相关文章

  1. 在VS的EF中连接MySQL

    VS没有主动提供那些繁多的连接器,需要的话得自己再安装这些第三方程序包. MySQL为windows平台开发者提供了许多程序包:http://dev.mysql.com/downloads/windo ...

  2. go语言中操作mysql的方法

    需要下载指定的golang的mysql驱动包 > go get github.com/go-sql-driver/mysql 下面的例子: package main; import ( &quo ...

  3. ADO.NET EF 中的实体修改方法

    http://www.cnblogs.com/zfz15011/archive/2010/05/30/1747486.html 1.传统修改模式,看下列代码 using (NorthwindEntit ...

  4. EF中使用Select new 方法中字段值替换的问题

    前提需要替换查询得到的List当中的某个字段的值,替换规则有一个mapping关系 尝试代码 有问题 无法获取任何数据 /// <summary> /// 获取Treegrid的List ...

  5. 转 ef中使用mysql步骤--Entity Framework 6 with MySql

    原文:http://lvasquez.github.io/2014/11/18/EntityFramework-MySql/ For the Entity Framework 6 support we ...

  6. EF中的MySql返回 DataTable公共类库

    public static class SqlHelper { /// <summary> /// EF SQL 语句返回 dataTable /// </summary> / ...

  7. Shell脚本中执行mysql的几种方式(转)

    Shell脚本中执行mysql的几种方式(转) 对于自动化运维,诸如备份恢复之类的,DBA经常需要将SQL语句封装到shell脚本.本文描述了在Linux环境下mysql数据库中,shell脚本下调用 ...

  8. EF(EntityFramework)与mysql使用,序列化问题[System.ObjectDisposedException]

    在EF 中使用mysql关联取数据时,如果当前实体中包含另一个实体的list成员,而这个成员为空的话,在json序列化的时候就会报错: '((System.Data.Entity.DynamicPro ...

  9. windows中Navicat连接centos中的mysql报:1130-Host '192.168.xxx.1' is not allowed to connect to this MySQL解决方法

    解决方法: 在centos中登录mysql输入下面指令: grant all PRIVILEGES on *.* to ' WITH GRANT OPTION;

随机推荐

  1. 玩转laravel5.4的入门动作(一)

    安装前 1 laravel是用composer来做的依赖关系,所以先下载composer  下载地址在这里https://getcomposer.org/download/   windows lin ...

  2. zabbix监控windows系统CPU使用率

    参考网站:https://blog.csdn.net/reblue520/article/details/76287113 Zabbix 自带的模块没有 CPU 使用率(百分比)这个监控项,我们可以通 ...

  3. 数学公式 AS3应用

    普通做法: var pA:Point=new Point(100,100); var pB:Point=new Point(300,200); var dx:Number=pA.x-pB.x; var ...

  4. remote Request

    import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; ...

  5. Java 跨域 CrossOrigin注解 Filter拦截 Nginx配置

    说明 资源请求的发起方与请求的资源不在同一个域中的: 一般的,只要网站的[协议名protocol].[主机host].[端口号port]这三个中的任意一个不同,网站间的数据请求与传输便构成了跨域调用: ...

  6. gulp 用法 小结

    前端们,gulp该用起来了,简单的demo入门 gulp.grunt前端自动化工具,只有用过才知道多么重要. 作者:一文不提来源:博客园|2015-05-28 10:35 移动端 收藏 分享 gulp ...

  7. Linux下tar.gz 安装

    将安装文件拷贝至你的目录中 如果是以root身份登录上的,就将软件拷贝至/root中. cp xxx.tar.gz /root 解压缩包 tar xvzf xxx.tar.gz 切换到安装目录下 cd ...

  8. SSL原理分析

    SSL协议的工作流程: 服务器认证阶段:       1)客户端向服务器发送一个开始信息“Hello”以便开始一个新的会话连接:      2)服务器根据客户的信息确定是否需要生成新的主密钥,如需要则 ...

  9. Android通过DeepLink方式跳转其他App传递参数

    网上对于安卓DeepLink方式跳转传递参数的例子较少,说的也不客观,实践之后发现还是有一些坑.其实为什么要用DeepLink方式跳转,有些是因为引流的原因,他们希望通过网页就能直接跳转到App的界面 ...

  10. luoguP1004 方格取数(四维DP)

    题目链接:https://www.luogu.org/problemnew/show/P1004 思路: 这道题是四维DP的模板题,与luoguP1006传纸条基本相似,用f[i][j][k][l]表 ...