EF框架执行原生SQL语句

EF框架执行原生SQL语句

Scroll Down

1223.jpg

EF 支持开放底层的 ADO.NET 框架,DbContext有三种常用方法

1、DbSet.SqlQuery         

//查询并返回Entities

2、DbContext.Database.SqlQuery

//执行某一个查询,并可以将返回集转换为某一对象

3、DbContext.Database.ExecuteSqlCommand  

//执行某一并无返回集的SQL 命令,例如UPDATE,DELETE操作

1.执行无参数sql:

string sql = "select * from IntegralInfo where convert(nvarchar,getdate(),23)='{0}' and status=1 and userinfoid='{1}'";

sql = string.Format(sql, DateTime.Now.ToString("yyyy-MM-dd"), uid);

var IntegralInfoObj = db.Database.SqlQuery(sql).FirstOrDefault();

2.执行有参数sql:

var IntegralInfoObj = db.Database.SqlQuery("select * from IntegralInfo

where convert(nvarchar,getdate(),23)=@time and status=1 and userinfoid=@uid",

new SqlParameter("@time", DateTime.Now.ToString("yyyy-MM-dd")),

new SqlParameter("@uid", uid)).FirstOrDefault();

3、执行Update语句

var res=db.Database.ExecuteSqlCommand("update admin set password='123456'");