A. 如何得到EF查询生成的sql
在EF 4.1中,我们可以直接调用DbQuery<>的ToString()方法得到所生成的SQL。
using (var context = new MyDbContext())
{
var people = from p in context.People
where p.PersonID > 100
select p;
string sql = people.ToString();
}
所生成的SQL是:
SELECT
[Extent1].[PersonID] AS [PersonID],
[Extent1].[Name] AS [Name]
FROM [dbo].[People] AS [Extent1]
WHERE [Extent1].[PersonID] > 100
大 家应该已经猜到,这里的ToString()方法其实也就是调用了ObjectQuery<>的ToTraceString()方法。 DbQuery<>.ToString() ==> System.Data.Entity.Internal.Linq.InternalQuery<>.ToString()方法,此方法 在.NET Reflector得到的实现是这样的:
public override string ToString()
{
return this._objectQuery.ToTraceString();
}
B. 如何在EF中直接运行SQL命令
EF model first方式, 你的DB是继承ObjectContext
using (MyObjectContext db = new MyObjectContext() )
{
string sql = “ select columnA, columnB from TableA where 1 = 1 ”;
db.ExecuteStoreQuery<TableAObject>手迅(sql).ToList();//租猛TableAObject就是你定义的对象,对象属性就是columnA, columnB
}
code first, 你的db是继承DbContext
using (MyDbContext db = new MyDbContext() )
{
string sql = “ select columnA, columnB from TableA where 1 = 1 ”;
db.TableAObject.SqlQuery(sql).ToList();//TableAObject就是在MyDbContext 定义的对象
}
这里只是列举查询的方式,仅供参考,一毕型此般新增 删除 或者修改 用对象的方式比较多,如果是sql,一般是
db.Database.ExecuteSqlCommand(sqlString)
C. EF怎么使用SQL语句查询到结果然后映射到自定义实体去
给你举个例子:
staticvoidMain(string[]args)
{
using(MyDBEntitiesen=newMyDBEntities())
{
varp1=en.People.First(x=>
x.Name=="Jim");
Console.WriteLine(p1.Age);
varp2=en.Database.SqlQuery<Person>(
@"selecttop1*fromperson
wherename='Jim'")
.First();
Console.WriteLine(p2.Age);
//p1p2是同一个记录
}
Console.ReadLine();
}
D. 如何在EF中直接运行SQL命令
在 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操作;后者是执谈汪行某一个查询,并可以将返回集转换为某一对象。
E. 如何在EF中直接运行SQL命令
http://..com/link?url=-B5UeGGl9eOYqbI-n-2QoN_q9j1bzVJeHesY8hUzdHGOQgC-xYS9hScodFNUAzykAZOqbYETj7MS
参考资料在这里你可以看看
F. ef使用sql语句查询单个数据,比如我要查询某表里面的某一个值,该怎么用。谢谢大神
declare
varchar temp(10)
select @temp=z from DB:A where ...
if(@temp==1)
select * from DB:B where...
else if(@temp==2)
select * from DB:C where...
else if(@temp==3)
select * from DB:D where...
这个思路应该是这样的,你自己把代码补充完整,数据类型定好,希望能帮到你