在EF4.1,API的名字 有了些许改变,DbContext.Database就是对应于数据库端信息的封装。执行SQL命令也自然从Database类型开始。对应于ExecuteStoreCommand和ExecuteStoreQuery<T>的是Database.ExecuteSqlCommand和Database.SqlQuery<T>。
1.执行command String
using (var ctx = new MyDbContext()) { ctx.Database.ExecuteSqlCommand("UPDATE Person SET Name = ‘Michael‘ WHERE PersonID = 1"); }
2.执行query String
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; } }
在EF4(.NET 4)中,我们有了全新的API:ObjectContext.ExecuteStoreCommand(...)和 ObjectContext.ExecuteStoreQuery<T>(...)。从函数名不难知道前者是为了执行某一并无返回集的SQL 命令,例如UPDATE,DELETE操作;后者是执行某一个查询,并可以将返回集转换为某一对象。
1.执行command String
using (var ctx = new MyObjectContext()) { ctx.ExecuteStoreCommand("UPDATE Person SET Name = ‘Michael‘ WHERE PersonID = 1"); }
2.执行query String
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; } }
时间: 2024-10-07 23:10:32