这部分介绍下再EF中如何使用SQL语句进行查询,主要是两个ExecuteSqlCommand和SqlQuery。ExecuteSqlCommand只会返回受影响的行数,因此是用于创建、删除、更新。而SqlQuery会返回查询后的结果。因此SqlQuery适用于查询数据。
插入数据
using (UserContext db = new UserContext())
{
var p_name = new SqlParameter("@name", "张三");
var p_pwd = new SqlParameter("@pwd", 123456);
var result = db.Database.ExecuteSqlCommand(@"insert into [CodeFirstDb].[dbo].[User](UserName,Password) values (@name,@pwd)", p_name, p_pwd);
Console.WriteLine("插入了{0}行数据",result);
}
更新数据
using (UserContext db = new UserContext())
{
var p_name = new SqlParameter("@name", "张三");
var p_pwd = new SqlParameter("@pwd", 123456);
var result = db.Database.ExecuteSqlCommand(@"UPDATE [CodeFirstDb].[dbo].[User]
SET Password = @pwd
WHERE UserName = @name;", p_pwd, p_name);
Console.WriteLine("更新了{0}行数据",result);
}
微软也提供了另一种参数传递的方式:占位符
using (UserContext db = new UserContext())
{
var result = db.Database.ExecuteSqlCommand(@"UPDATE [CodeFirstDb].[dbo].[User]
SET Password = @p0
WHERE UserName = @p1;","123123","张三");
Console.WriteLine("更新了{0}行数据",result);
}
占位符从@p0开始,参数值一一对应即可。
删除数据
using (UserContext db = new UserContext())
{
var p_name = new SqlParameter("@name", "张三");
var result = db.Database.ExecuteSqlCommand(@"DELETE FROM [CodeFirstDb].[dbo].[User] WHERE UserName = @name", p_name);
Console.WriteLine("删除了{0}行数据", result);
}
查询数据
var p_name = new SqlParameter("@name", "Curry");
using (UserContext db = new UserContext())
{
var result1 = db.Users.SqlQuery(@"select * from[CodeFirstDb].[dbo].[User]whereUserName=@name", p_name).FirstOrDefault();
Console.WriteLine(result1.Password);
result1.Password = "123asd";
var result2 = db.Database.SqlQuery<User>("select * from[CodeFirstDb].[dbo].[User]whereUserName='Alan'").FirstOrDefault();
Console.WriteLine(result2.Password);
result2.Password = "123asd";
var result3 = db.Database.SqlQuery<User>("select * from[CodeFirstDb].[dbo].[User]whereUserName='张三'").FirstOrDefault();
Console.WriteLine(result3.Password);
result3.Password = "123asd";
db.Entry<User>(result3).State=System.Data.Entity.EntityState.Modified;//通知数据上下文,这条记录也被修改了
db.SaveChanges();
}
输出结果都是123asd,但是数据库中Alan的密码并没有修改说明使用.Database.SqlQuery<>查询到的数据是无法保存到数据库的,如果想保存,需要通知上下文。