1、安装插件

在使用Visual Studio 2013添加ADO.NET实体数据模型新建连接时,默认是没有Mysql选项的。此时我们需要安装两个东西:

1、mysql-for-visualstudio:Mysql的Visual Studio插件,推荐1.2.3版本

2、mysql-connector-net:.net连接Mysql的程序,推荐6.8.3,版本。如果安装高版本可能导致一系列问题。详见:http://blog.csdn.net/niewq/article/details/41877301

2、新建ADO.NET实体数据模型

2、1、按图操作,添加实体数据模型:

2.2、一切进展貌似都很顺利。接下来你可能会看到Visual Studio给出了如下的提示:

2.3、解决方法:在NuGet的控制台输入以下命令:

Install-Package EntityFramework -Version 6.0.0
     Install-Package EntityFramework.zh-Hans -Version 6.0.0
     Install-Package MySql.Data.Entity.EF6

每个命令输入之后按回车执行,你会发现前两个都很顺利,但是第三个却报错了:

此时我们不通过NuGet添加这个引用,具体步骤为将MySQL Connector Net 6.8.3\Assemblies\v4.5(视你的项目使用的.net版本而定,我的是.net 4.5)下的所有dll文件引用进来。我的机器上安装目录如下:

全部引用

然后在应用程序配置文件中添加:<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"></provider>

<?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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"></provider>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>

然后,一定要重新生成项目!!!

2.4、继续下面的步骤,成功。

3、Mysql数据库改动

接下来,就是从数据库选择表以生成EDMX文件,但是在此过程中,你可能会遇到下列问题:

VS给出了一堆的提示,但是重点就是红框内的:表“TableDetails”中列“IsPrimaryKey”的值为 DBNull。这个问题的解决方案在。我们按照文中所说,设置数据库testbak(我用的数据库):

1、重启数据库服务器。

2、use testbak;

3、set global optimizer_switch='derived_merge=OFF';

再去尝试一次,成功!!!

解决方案窗口多了很多文件:

每个实体数据模型生成一个context类,数据库每个表生成一个entity类。在Model1.edmx中包含的两个重要的文件Model1.Context.tt和Model1.tt。第一个是用于生成Context类的T4模板,第二是用于生成表映射实体类(POCO类,POCO:Plain Old CLR Object)的T4模板。

Model1.Context.cs是从System.Data.Entity.DbContext类继承。EF4.1中则是从ObjectContext类继承。DbContext类与ObjectContext类似,它对ObjcetContext类进行包装更利于开发的三种模式:CodeFirst、Model First、Database First。

4、DbContext

DbContext是EntityFramework很重要的部分,连接域模型与数据库的桥梁,是与数据库通信的主要类。

DbContext主要负责以下活动:

EntitySet:DbContext包含了所有映射到表的entities

Querying将Linq-To-Entities转译为Sql并发送到数据库

Change Tracking从数据库获取entities后保留并跟踪实体数据变化

Persisting Data根据entity状态执行Insert、update、delete命令

CachingDbContext的默认第一级缓存,在上下文中的生命周期中存储entity

Manage RelationshipDbContext在DbFirst模式中使用CSDL、MSL、SSDL管理对象关系,Code first中使用fluent api 管理关系

Object MaterializationDbContext将物理表转成entity实例对象

//DbContext实例化:
using (var ctx = newSchoolDBEntities())
{
//Can perform CRUD operation using ctx here..
} //将DbContext转为ObjectContext
using (var ctx = newSchoolDBEntities())
{
var objectContext = (ctx as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext;
//use objectContext here..
}

详见:http://www.cnblogs.com/xuf22/articles/5513283.html

5、增删改查操作

5.1 IDAL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace ADO.NETEFDemo
{
public interface IDAL<T> where T : class,new()
{
/// <summary>
/// 增
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
int Add(T model); /// <summary>
/// 删
/// </summary>
/// <param name="whereLambda"></param>
/// <returns></returns>
int Delete(Expression<Func<T, bool>> whereLambda); /// <summary>
/// 改
/// </summary>
/// <param name="whereLambda"></param>
/// <param name="propertyNames"></param>
/// <param name="perpertyValues"></param>
/// <returns></returns>
int Update(Expression<Func<T, bool>> whereLambda, string[] propertyNames, object[] perpertyValues); /// <summary>
/// 查
/// </summary>
/// <param name="whereLambda"></param>
/// <returns></returns>
List<T> GetModelList(Expression<Func<T, bool>> whereLambda);
}
}

5.2 DAL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace ADO.NETEFDemo
{
public class DAL<T> : IDAL<T> where T : class,new()
{
/// <summary>
/// 增
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public int Add(T model)
{
using (testbakEntities db = new testbakEntities())
{
db.Set<T>().Add(model);
return db.SaveChanges();
}
} /// <summary>
/// 删
/// </summary>
/// <param name="whereLambda"></param>
/// <returns></returns>
public int Delete(Expression<Func<T, bool>> whereLambda)
{
using (testbakEntities db = new testbakEntities())
{
var dbQuery = db.Set<T>(); //先查询 对应表的 集合
var list = dbQuery.Where(whereLambda).ToList(); //遍历集合 里要删除的元素
foreach (var item in list)
{
//标记为 删除状态
dbQuery.Remove(item);
}
return db.SaveChanges();
}
} /// <summary>
/// 改
/// </summary>
/// <param name="whereLambda"></param>
/// <param name="propertyNames"></param>
/// <param name="perpertyValues"></param>
/// <returns></returns>
public int Update(Expression<Func<T, bool>> whereLambda, string[] propertyNames, object[] perpertyValues)
{
using (testbakEntities db = new testbakEntities())
{
//1、查询要修改的对象集合
var list = db.Set<T>().Where<T>(whereLambda).ToList(); //2、获取要修改的对象的类型
Type t = typeof(T); //3、循环要修改的实体对象,并根据要修改的属性名修改对象对应的属性值
foreach (var item in list)
{
//循环 要修改的属性 名称, 并 反射取出 t 中的 属性对象
for (int index = ; index < propertyNames.Length; index++)
{
//获取要修改的属性名
string pName = propertyNames[index]; //获取属性对象
PropertyInfo pi = t.GetProperty(pName); //调用属性对象的 SetValue方法 为当前循环的 item对象 对应的属性赋值
pi.SetValue(item, perpertyValues[index], null);
}
}
return db.SaveChanges();
}
} /// <summary>
/// 查
/// </summary>
/// <param name="whereLambda"></param>
/// <returns></returns>
public List<T> GetModelList(Expression<Func<T, bool>> whereLambda)
{
using (testbakEntities db = new testbakEntities())
{
return db.Set<T>().Where(whereLambda).ToList();
}
}
}
}

5.3 BLL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace ADO.NETEFDemo
{
public static class BLL<T> where T : class,new()
{
private static IDAL<T> dal = new DAL<T>(); /// <summary>
/// 新增
/// </summary>
/// <param name="model"></param>
public static int Add(T model)
{
return dal.Add(model);
} /// <summary>
/// 删除
/// </summary>
/// <param name="whereLambda"></param>
public static int Delete(Expression<Func<T, bool>> whereLambda)
{
return dal.Delete(whereLambda);
} /// <summary>
/// 修改
/// </summary>
/// <param name="whereLambda"></param>
/// <param name="propertyNames"></param>
/// <param name="perpertyValues"></param>
/// <returns></returns>
public static int Update(Expression<Func<T, bool>> whereLambda, string[] propertyNames, object[] perpertyValues)
{
return dal.Update(whereLambda, propertyNames, perpertyValues);
} /// <summary>
/// 查询
/// </summary>
/// <param name="whereLambda"></param>
/// <returns></returns>
public static List<T> GetModelList(Expression<Func<T, bool>> whereLambda)
{
return dal.GetModelList(whereLambda);
}
}
}

5.4 调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace ADO.NETEFDemo
{
class Program
{
static void Main(string[] args)
{
GetArticleList(); AddArticle(); GetArticleList(); UpdateArticle(); GetArticleList(); DeleteArticel(); GetArticleList(); Console.ReadKey();
} /// <summary>
/// 更新
/// </summary>
private static void UpdateArticle()
{
int result = BLL<t_crobot_reship_articles>
.Update(e => e.title.Contains("EF"), new[] { "title", "update_time" },
new object[] { "我是使用EF修改过标题的文章", DateTime.Now });
if (result >= )
{
Console.WriteLine("更新成功");
}
else
{
Console.WriteLine("更新失败");
}
Console.WriteLine();
} /// <summary>
/// 删除
/// </summary>
private static void DeleteArticel()
{
int result = BLL<t_crobot_reship_articles>.Delete(e => e.title.Contains("EF"));
if (result >= )
{
Console.WriteLine("删除成功");
}
else
{
Console.WriteLine("删除失败");
}
Console.WriteLine();
} /// <summary>
/// 新增
/// </summary>
private static void AddArticle()
{
t_crobot_reship_articles model = new t_crobot_reship_articles();
model.create_time = DateTime.Now;
model.module_id = ;
model.adword_id = ;
model.pick_id = ;
model.vote_id = "";
model.title = "我是使用EF添加的文章";
model.content_id = ;
model.release_url = "http://www.sss.com";
model.state = true;
int result = BLL<t_crobot_reship_articles>.Add(model);
if (result >= )
{
Console.WriteLine("新增成功");
}
else
{
Console.WriteLine("新增失败");
}
Console.WriteLine();
} /// <summary>
/// 获取文章列表
/// </summary>
private static void GetArticleList()
{
List<t_crobot_reship_articles> articleList = BLL<t_crobot_reship_articles>
.GetModelList(e => e.state == true); Console.WriteLine("文章总数:" + articleList.Count.ToString());
foreach (t_crobot_reship_articles model in articleList)
{
Console.WriteLine("标题:" + model.title);
} Console.WriteLine();
}
}
}

5.5 结果

6、小结

文章中需要使用的插件下载地址:mysql-for-visualstudio-1.2.3.zipmysql-connector-net-6.8.3.zip

具体的操作步骤并不一定按文中所述的来。

使用VS2013 + EF6 + .NET4.5 连接Mysql数据库的更多相关文章

  1. 刚刚完成了在vs2013中通过 ef连接mysql数据库的工作。感觉没有想象中的简单。试了n次终于成功。故记录成功的方法,希望可以帮到大家

    分两种情况,如果你是用entity framework 5.0的时候 mysql-connector-net的版本不是很重要. MySQL For VisualStudio的版本也不重要 (这个不装就 ...

  2. 使用VS2013 + EF6 连接Mysql数据库

    使用VS2013 + EF6 + .NET4.5 连接Mysql数据库 1.安装插件 在使用Visual Studio 2013添加ADO.NET实体数据模型新建连接时,默认是没有Mysql选项的.此 ...

  3. Vs2013 使用EF6 连接mysql数据库

    最近在使用MySQL数据库,在使用EF框架连接MySQL数据库时发现了一个问题,使用DB First创建实体对象的时候会出现如下图的错误:您的项目引用了最新版实体框架….. (如下图)或者会出现新建实 ...

  4. VS2015 +EF6 连接MYSQL数据库生成实体

      VS2015 +EF6 连接MYSQL数据库生成实体   已安装软件:VS2015                       XAMPP Control Panel(Mysql服务器)      ...

  5. Entity Framework连接Mysql数据库并生成Model和DAL层

    Entity Framework (EF,ADO.NET Entity Framework)是微软官方提供的.NET平台的ORM框架.相比于LINQ TO SQL,EF框架具有很明显的优势: EF框架 ...

  6. EntityFramework 6.0< Code First > 连接 Mysql数据库(转)

    http://blog.csdn.net/kmguo/article/details/19650299 网上有很多关于用EntityFrame来连接Mysql数据库的教程,可是很多并不靠谱,转载的太多 ...

  7. EntityFramework 6.0< Code First > 连接 Mysql数据库

    网上有很多关于用EntityFrame来连接Mysql数据库的教程,可是很多并不靠谱,转载的太多了.找了很久,总算是配置好了,现在分享一下. 一,安装:     1.开发环境: VS2013与EF6 ...

  8. 转载:EntityFramework 6.0< Code First > 连接 Mysql数据库

    转载自:http://blog.csdn.net/kmguo/article/details/19650299 网上有很多关于用EntityFrame来连接Mysql数据库的教程,可是很多并不靠谱,转 ...

  9. visualC/C++连接MySql数据库

    vs连接数据库其实就是将mysql数据库.h头文件接口.lib链接文件和dll执行文件加入到项目中.下面是配置如何加入. 转于http://www.cnblogs.com/justinzhang/ar ...

随机推荐

  1. JAVA课程设计——单机版五子棋

    JAVA课程设计--单机版五子棋 1.团队名称.团队成员介绍 团队名称:Gomoku小分队 团队成员: 网络1512 201521123038 游舒婷(组长) 网络1512 201521123043 ...

  2. 201521123016《Java程序设计》第14周学习总结

    1. 本周学习总结 2. 书面作业 1. MySQL数据库基本操作 建立数据库,将自己的姓名.学号作为一条记录插入.(截图,需出现自己的学号.姓名) 在自己建立的数据库上执行常见SQL语句(截图) - ...

  3. 201521044091 《Java程序设计》第13周学习总结

    1. 本周学习总结 以你喜欢的方式(思维导图.OneNote或其他)归纳总结多网络相关内容.

  4. 升级Linux tar &&解决某用tar解压失败的tar包

    今天解压个文件,出来很多这样的: /bin/tar: Ignoring unknown extended header keyword `SCHILY.dev'/bin/tar: Ignoring u ...

  5. 跨Storyboard调用

    在开发中我们会有这种需求从一个故事板跳到另一个故事板 modal UIStoryboard *secondStoryboard = [UIStoryboard storyboardWithName:@ ...

  6. ui-router

    学习历程:1 ng-router --> 2 location  --> 3 $location -->  4 promise  --> 5 html5 history  -- ...

  7. unable to dequeue a cell with identifier MealTableViewCell

    1 问题描述 Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable ...

  8. 第4章 同步控制 Synchronization ---哲学家进餐问题(The Dining Philosophers)

    哲学家进餐问题是这样子的:好几位哲学家围绕着餐桌坐,每一位哲学家要么思考,要么等待,要么就吃饭.为了吃饭,哲学家必须拿起两支筷子(分放于左右两端).不幸的是,筷子的数量和哲学家相等,所以每支筷子必须由 ...

  9. tomcat manager 的用户权限配置,及环境变量CATALINA_HOME的错位问题

    因为tomcat的manager是管理其他项目的发布.删除等操作的管理项目,所以需要为其设置登陆用户和密码,以及用户相应的访问权限,配置如下: tomcat-users.xml需要添加如下内容: &l ...

  10. 【Kafka】操作命令

    生产者 ./kafka-console-producer.sh --broker-list --topic norm 消费者 ./kafka-console-consumer.sh --zookeep ...