C# 在EF中直接运行SQL命令
时间:2021-07-01 10:21:17
帮助过:69人阅读
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)中,我们有了全新的API:ObjectContext.ExecuteStoreCommand(...)和 ObjectContext.ExecuteStoreQuery<T>
(...)。从函数名不难知道前者是为了执行某一并无返回集的SQL 命令,例如UPDATE,DELETE操作;后者是执行某一个查询,并可以将返回集转换为某一对象。
using (
var ctx =
new MyObjectContext())
{
ctx.ExecuteStoreCommand("UPDATE Person SET Name = ‘Michael‘ WHERE PersonID = 1");
}
复制代码
using (
var ctx =
new MyObjectContext())
{
var peopleViews = ctx.ExecuteStoreQuery<PersonView>(
"SELECT PersonID, Name FROM Person");
}
public class PersonView
{
public int PersonID {
get;
set; }
public string Name {
get;
set; }
}
复制代码
现在有了EF4.1,API的名字又有了些许改变。如果说DbContext将ObjectContext做了包装,那么DbContext.Database就是对应于数据库端信息的封装。执行SQL命令也自然从Database类型开始。对应于ExecuteStoreCommand和ExecuteStoreQuery<T>的是Database.ExecuteSqlCommand和Database.SqlQuery<T>
。
using (
var ctx =
new MyDbContext())
{
ctx.Database.ExecuteSqlCommand("UPDATE Person SET Name = ‘Michael‘ WHERE PersonID = 1");
}
复制代码
using (
var ctx =
new MyDbContext())
{
var 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
C# 在EF中直接运行SQL命令
标签:c# pre net data 返回 html procedure .sql comm