首页 > 代码库 > 在EF中直接运行SQL命令

在EF中直接运行SQL命令

<style></style>

一、在 EF第一个版本(.NET 3.5 SP1)中

通过将ObjectContext.Connection转换为EntityConnection,

再把 EntityConnection.StoreConnection转换为SqlConnection。

有了这个SqlConnection,我们再创建 SqlCommand便能顺利运行SQL命令了。

例如:

      EntityConnection entityConnection = (EntityConnection)ctx.Connection;
      DbConnection storeConnection = entityConnection.StoreConnection;
      DbCommand cmd = storeConnection.CreateCommand();
      cmd.CommandType = System.Data.CommandType.StoredProcedure;
      cmd.CommandText = "[PRO_USER_DIGITALCARD_CHECK]";

      ....

二、在EF4(.NET 4)中

ObjectContext.ExecuteStoreCommand(...)     执行某一并无返回集的SQL 命令,例如ADD,UPDATE,DELETE操作

ObjectContext.ExecuteStoreQuery<T>(...)     执行某一个查询,并可以将返回集转换为某一对象

using (var ctx = new MyObjectContext()){    int result = ctx.ExecuteStoreCommand("UPDATE Person SET Name = ‘Michael‘ WHERE PersonID = 1");}

 

using (var ctx = new MyObjectContext()){    IEnumerable<PersonView> peopleViews = ctx.ExecuteStoreQuery<PersonView>("SELECT PersonID, Name FROM Person");}public class PersonView{    public int PersonID { get; set; }    public string Name { get; set; }}

 

三、在EF4.1中

DbContext将ObjectContext做了包装,

DbContext.Database就是对应于数据库端信息的封装

执行SQL命令也从Database类型开始

 

using (var ctx = new MyDbContext()){    int result = ctx.Database.ExecuteSqlCommand("UPDATE Person SET Name = ‘Michael‘ WHERE PersonID = 1");}

 

using (var ctx = new MyDbContext()){    IEnumerable<PersonView> peopleViews = ctx.SqlQuery<PersonView>("SELECT PersonID, Name FROM Person").ToList();}public class PersonView{    public int PersonID { get; set; }    public string Name { get; set; }}

 原文地址:

http://www.cnblogs.com/chengxiaohui/articles/2092001.html

在EF中直接运行SQL命令