如何在EF中直接运行SQL命令
发布网友
发布时间:2022-04-08 03:19
我来回答
共2个回答
懂视网
时间:2022-04-08 07:40
using (var context = new TestDBEntities())
2 {
3 var query = from p in context.Parents
4 where p.Name == "zhaokun"
5 select p;
6
7 ObjectQuery<Parent> parents = query as ObjectQuery<Parent>;
8 if (parents != null)
9 {
10 string sql = parents.ToTraceString();
11 }
12 }
totracestring
这里所生成的SQL为:
1 [Extent1].[ParentID] AS [ParentID],
2 [Extent1].[Name] AS [Name]
3 FROM [dbo].[Parent] AS [Extent1]
4 WHERE N‘zhaokun‘=[Extent1].[Name]
sqlone
在EF 4.1中,我们可以直接调用DbQuery<>的ToString()方法得到所生成的SQL。
1 using (var context = new MyDbContext())
2 {
3 var people = from p in context.People
4 where p.PersonID > 100
5 select p;
6
7 string sql = people.ToString();
8 }
tostring
所生成的SQL是:
1 SELECT
2 [Extent1].[PersonID] AS [PersonID],
3 [Extent1].[Name] AS [Name]
4 FROM [dbo].[People] AS [Extent1]
5 WHERE [Extent1].[PersonID] > 100
sqltwo
这里的ToString()方法其实也就是调用了ObjectQuery<>的ToTraceString()方法。 DbQuery<>.ToString() ==> System.Data.Entity.Internal.Linq.InternalQuery<>.ToString()方法,此方法 在.NET Reflector得到的实现是这样的:
1 public override string ToString()
2 {
3 return this._objectQuery.ToTraceString();
4 }
tostring()
看书得到!
EF查询生成的SQL
标签:
热心网友
时间:2022-04-08 04:48
相信不少使用EF的同志们已经知道如何在EF中运行SQL命令了。我在这里简单总结下,希望对大家学习EF有所帮助!
在 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.StoredProcere;
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; }
}