连接mysql数据库2013_使用VS2013 + EF6 + .NET4.5 连接Mysql数据库

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、按图操作,添加实体数据模型:

2b166fde2b678171c1293b88ae8e9860.png

4ff9885cd8e561f2873268116a1534a2.png

2453be6452e159beb67c5e7481806505.png

c79d61cb68a0cceb94384b81c95501b5.png

9f3ad6654387a46c8808403c0e48cc15.png

23cceeb8f06af3a11ffa94e9053e6a58.png

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

fdb4f5245a19d5ac2187621863c097c2.png

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

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

14aaae6d6de84f4d5edab499f8094870.png

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

e7e87387cf416f5f6015d60c68750e9b.png

全部引用

7ae558812b4f334c2f6e9fc0da13be88.png

然后在应用程序配置文件中添加:

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

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

8128db785b4688f3c564a4d10d9ab607.png

3、Mysql数据库改动

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

5cd7ce17714200dc02187672e44d6982.png

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

1、重启数据库服务器。

2、use testbak;

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

a1ffd877490e196aef32d32de39efbc8.png

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

41c553dd72b972b549e1fa6611efcb3f.png

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

5dca98af88432b45ae177314473add29.png

每个实体数据模型生成一个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很重要的部分,连接域模型与数据库的桥梁,是与数据库通信的主要类。

1bfb75f1141d4dcddf5365777df4e40b.png

DbContext主要负责以下活动:

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

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

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

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

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

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

Object Materialization:DbContext将物理表转成entity实例对象

//DbContext实例化:

using (var ctx =newSchoolDBEntities())

{//Can perform CRUD operation using ctx here..

}//将DbContext转为ObjectContext

using (var ctx =newSchoolDBEntities())

{var objectContext = (ctx asSystem.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext;//use objectContext here..

}

5、增删改查操作

5.1 IDAL

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Linq.Expressions;usingSystem.Text;usingSystem.Threading.Tasks;namespaceADO.NETEFDemo

{public interface IDAL where T : class,new()

{///

///增///

///

///

intAdd(T model);///

///删///

///

///

int Delete(Expression>whereLambda);///

///改///

///

///

///

///

int Update(Expression> whereLambda, string[] propertyNames, object[] perpertyValues);///

///查///

///

///

List GetModelList(Expression>whereLambda);

}

}

5.2 DAL

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Linq.Expressions;usingSystem.Reflection;usingSystem.Text;usingSystem.Threading.Tasks;namespaceADO.NETEFDemo

{public class DAL : IDAL where T : class,new()

{///

///增///

///

///

public intAdd(T model)

{using (testbakEntities db = newtestbakEntities())

{

db.Set().Add(model);returndb.SaveChanges();

}

}///

///删///

///

///

public int Delete(Expression>whereLambda)

{using (testbakEntities db = newtestbakEntities())

{var dbQuery = db.Set();//先查询 对应表的 集合

var list =dbQuery.Where(whereLambda).ToList();//遍历集合 里要删除的元素

foreach (var item inlist)

{//标记为 删除状态

dbQuery.Remove(item);

}returndb.SaveChanges();

}

}///

///改///

///

///

///

///

public int Update(Expression> whereLambda, string[] propertyNames, object[] perpertyValues)

{using (testbakEntities db = newtestbakEntities())

{//1、查询要修改的对象集合

var list = db.Set().Where(whereLambda).ToList();//2、获取要修改的对象的类型

Type t = typeof(T);//3、循环要修改的实体对象,并根据要修改的属性名修改对象对应的属性值

foreach (var item inlist)

{//循环 要修改的属性 名称, 并 反射取出 t 中的 属性对象

for (int index = 0; index < propertyNames.Length; index++)

{//获取要修改的属性名

string pName =propertyNames[index];//获取属性对象

PropertyInfo pi =t.GetProperty(pName);//调用属性对象的 SetValue方法 为当前循环的 item对象 对应的属性赋值

pi.SetValue(item, perpertyValues[index], null);

}

}returndb.SaveChanges();

}

}///

///查///

///

///

public List GetModelList(Expression>whereLambda)

{using (testbakEntities db = newtestbakEntities())

{return db.Set().Where(whereLambda).ToList();

}

}

}

}

5.3 BLL

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Linq.Expressions;usingSystem.Text;usingSystem.Threading.Tasks;namespaceADO.NETEFDemo

{public static class BLL where T : class,new()

{private static IDAL dal = new DAL();///

///新增///

///

public static intAdd(T model)

{returndal.Add(model);

}///

///删除///

///

public static int Delete(Expression>whereLambda)

{returndal.Delete(whereLambda);

}///

///修改///

///

///

///

///

public static int Update(Expression> whereLambda, string[] propertyNames, object[] perpertyValues)

{returndal.Update(whereLambda, propertyNames, perpertyValues);

}///

///查询///

///

///

public static List GetModelList(Expression>whereLambda)

{returndal.GetModelList(whereLambda);

}

}

}

5.4 调用

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceADO.NETEFDemo

{classProgram

{static void Main(string[] args)

{

GetArticleList();

AddArticle();

GetArticleList();

UpdateArticle();

GetArticleList();

DeleteArticel();

GetArticleList();

Console.ReadKey();

}///

///更新///

private static voidUpdateArticle()

{int result = BLL.Update(e=> e.title.Contains("EF"), new[] { "title", "update_time"},new object[] { "我是使用EF修改过标题的文章", DateTime.Now });if (result >= 0)

{

Console.WriteLine("更新成功");

}else{

Console.WriteLine("更新失败");

}

Console.WriteLine();

}///

///删除///

private static voidDeleteArticel()

{int result = BLL.Delete(e => e.title.Contains("EF"));if (result >= 0)

{

Console.WriteLine("删除成功");

}else{

Console.WriteLine("删除失败");

}

Console.WriteLine();

}///

///新增///

private static voidAddArticle()

{

t_crobot_reship_articles model= newt_crobot_reship_articles();

model.create_time=DateTime.Now;

model.module_id= 1;

model.adword_id= 20;

model.pick_id= 1;

model.vote_id= "1";

model.title= "我是使用EF添加的文章";

model.content_id= 1;

model.release_url= "http://www.sss.com";

model.state= true;int result = BLL.Add(model);if (result >= 0)

{

Console.WriteLine("新增成功");

}else{

Console.WriteLine("新增失败");

}

Console.WriteLine();

}///

///获取文章列表///

private static voidGetArticleList()

{

List articleList = BLL.GetModelList(e=> e.state == true);

Console.WriteLine("文章总数:" +articleList.Count.ToString());foreach (t_crobot_reship_articles model inarticleList)

{

Console.WriteLine("标题:" +model.title);

}

Console.WriteLine();

}

}

}

5.5 结果

8c059d1ba9c6de3b66d2772988d67970.png

6、小结

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值