使用 EF Code First + Mysql

这两天没事,研究EF 以往都是 连 mssql 微软亲儿子,换成了 mysql之后就问题百出,下面记录一下怎么使用 EF code first  +  mysql 数据库;

项目中,nuget先引入 EF 扩展 ;

如果本地有EF扩展了,可以使用 程序包管理控制台安装,命令如下。

PM> Install-Package EntityFramework -Version 6.0.0

然后nuget 安装    MySql.Data.Entity  这个扩展是mysql用来支持 EF 的

我这里引入的是 6.10.9 最新 版本 ;

引入扩展后,VS将自动生成了 配置文件 app.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>
    <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.10.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
      </provider>
    </providers>
  </entityFramework>
  <!-- 新增下方连接字符串 -->

  <connectionStrings>
    <add name="DataAccess" connectionString="Datasource=127.0.0.1;port=3306;Database=zyturo;uid=root;pwd=fubing;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
</configuration>

链接字符串的配置;

 <connectionStrings>
    <add name="DataAccess" connectionString="Datasource=127.0.0.1;port=3306;Database=zyturo;uid=root;pwd=fubing;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>

创建和数据库映射的关系实体类

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZY.Tour.EntityFramework
{
    public class TB_Admin
    {
        /// <summary>
        /// 管理员ID
        /// </summary>
        [Key]
        public Int32 Admin_ID { get; set; }
        /// <summary>
        /// 管理员登录账号
        /// </summary>
        [Required]
        public string Account { get; set; }
        /// <summary>
        /// 管理员登录密码
        /// </summary>
        [Required]

        public string Password { get; set; }
        /// <summary>
        /// 加密盐
        /// </summary>
        [Required]

        public string Salt { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public Nullable<DateTime> CreateTime { get; set; }
        /// <summary>
        /// 帮助注册人的ID
        /// </summary>
        public Int32 ParentID { get; set; }
        /// <summary>
        /// 最后登录IP
        /// </summary>
        public string LastLoginIP { get; set; }

        /// <summary>
        /// 管理员所在部门ID
        /// </summary>
        public Int32 Department_ID { get; set; }
    }
}

实体类属性上添加了 特性 (Attribute)  这块具体的说明可以参考 园友文章: https://www.cnblogs.com/dotnet261010/p/9111954.html

[Key] 表示主键,他是自动递增的 从0开始;

[Required] 表示不能为空

需要了解更多特性标注使用类,可以在对象浏览器 看 System.ComponentModel.DataAnnotations 命名空间下都有哪些特性的定义;

下面是我创建的一个DataAccess 类,用于操作数据库;

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZY.Tour.EntityFramework
{
    [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
    public class DataAccess : DbContext
    {
        public DataAccess() : base("name=DataAccess")
        {
        }
        public virtual DbSet<TB_Admin> Admin { get; set; }
    }
}
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]在 DbContent类上添加了一条标注,用于声明为生成为 mysql 的数据类型;

至此就可以正常使用了,我搭建了一个单员测试项目,测试通过;

 public void TestMethod1()
        {
            var da = new DataAccess();
            da.Admin.Add(new TB_Admin
            {
                Account = "fubing",
                CreateTime = DateTime.Now,
                Password = "123123",
                Salt = "123123"
            });
            da.SaveChanges();
            Assert.IsTrue(true);
        }

数据库被自动创建 并 创建 表和 数据了;

好了,记录完毕;

原文地址:https://www.cnblogs.com/fubing/p/11616128.html

时间: 2024-08-29 07:26:02

使用 EF Code First + Mysql的相关文章

[EF]vs15+ef6+mysql code first方式

写在前面 前面有篇文章,尝试了db first方式,但不知道是什么原因一直没有成功,到最后也没解决,今天就尝试下code first的方式. [EF]vs15+ef6+mysql这个问题,你遇到过么? 一个例子 步骤 mysql-for-visualstudio-1.2.4.msi 下载该文件,然后运行安装(如果没安装,请先安装). Connector/Net 下载该文件,并安装(如果没安装,请先安装) 使用Nuget安装EF 使用Nuget安装mysql提供程序. 在上面的步骤完成后,修改we

C# 之 EF CodeFirst创建MySQL数据库

MySQL安装好了,今天跟大家交流一下怎么利用EntityFramework的CodeFirst在MySQL数据库中创建数据库 目标框架:.NET Framework 4 第一步:新建一个项目,然后添加如下的引用,这些引用可以在NuGet中添加,也可以到官网中下载然后添加 第二步:在配置文件中添加数据库节点配置 <span style="font-family:Arial;font-size:10px;"><?xml version="1.0"?&

Error Code: 2006 - MySQL 鏈嶅姟鍣ㄥ凡绂荤嚎

将sql文件导入到mysql时候,就一直报这个错误.我试过网上各种方法都行不通.最后将下面一句执行了一下就可以了,而且没有重启mysql. SET GLOBAL max_allowed_packet=67108864; Error Code: 2006 - MySQL 鏈嶅姟鍣ㄥ凡绂荤嚎,布布扣,bubuko.com

EF Code First 配置的相关内容

I.实体间一对一的关系 添加一个PersonPhoto类,表示用户照片类 1 /// <summary> 2 /// 用户照片类 3 /// </summary> 4 public class PersonPhoto 5 { 6 [Key] 7 public int PersonId { get ; set ; } 8 public byte [] Photo { get ; set ; } 9 public string Caption { get ; set ; } // 标题

Inheritance with EF Code First: Part 2 – Table per Type (TPT)

In the previous blog post you saw that there are three different approaches to representing an inheritance hierarchy and I explained Table per Hierarchy (TPH) as the default mapping strategy in EF Code First. We argued that the disadvantages of TPH m

Inheritance with EF Code First: Part 1 – Table per Hierarchy (TPH)

以下三篇文章是Entity Framework Code-First系列中第七回:Entity Framework Code-First(7):Inheritance Strategy 提到的三篇.这三篇文章写的时间有点久远,还是在2010年,提到EF应该在4.1版本之前,使用的还是ObjectContext而不是现在的DbContext,内容供参考 -------------------------------------------------------------------------

ASP.NET Web API实践系列02,在MVC4下的一个实例, 包含EF Code First,依赖注入, Bootstrap等

本篇体验在MVC4下,实现一个对Book信息的管理,包括增删查等,用到了EF Code First, 使用Unity进行依赖注入,前端使用Bootstrap美化.先上最终效果: →创建一个MVC4项目,选择Web API模版. →在Models文件夹创建一个Book.cs类. namespace MyMvcAndWebApi.Models { public class Book { public int Id { get; set; } public string Name { get; set

EF Code First学习笔记

EF Code First学习笔记 初识Code First EF Code First 学习笔记:约定配置 Entity Framework 复杂类型 Entity Framework 数据生成选项DatabaseGenerated Entity Framework 并发处理 EF Code First 学习笔记:关系 Entity Framework Code First级联删除 EF Code First 学习笔记:表映射 EF Code First学习笔记:数据库创建 Entity Fr

Inheritance with EF Code First: Part 3 – Table per Concrete Type (TPC)

Inheritance with EF Code First: Part 3 – Table per Concrete Type (TPC) This is the third (and last) post in a series that explains different approaches to map an inheritance hierarchy with EF Code First. I've described these strategies in previous po