在 entityframework 中,我们可以使用 ExecuteStoreQuery 或 ExecuteStoreCommand 来执行 sql 查询。那么它们之间有什么区别(不同的场景)?
谢谢你。
在 entityframework 中,我们可以使用 ExecuteStoreQuery 或 ExecuteStoreCommand 来执行 sql 查询。那么它们之间有什么区别(不同的场景)?
谢谢你。
从MSDN可以看出区别
执行存储查询
直接针对返回一系列类型化结果的数据源执行查询。
和MSDN
执行存储命令
使用现有连接直接对数据源执行任意命令。
using (SchoolEntities context =
new SchoolEntities())
{
// The following three queries demonstrate
// three different ways of passing a parameter.
// The queries return a string result type.
// Use the parameter substitution pattern.
foreach (string name in context.ExecuteStoreQuery<string>
("Select Name from Department where DepartmentID < {0}", 5))
{
Console.WriteLine(name);
}
// Use parameter syntax with object values.
foreach (string name in context.ExecuteStoreQuery<string>
("Select Name from Department where DepartmentID < @p0", 5))
{
Console.WriteLine(name);
}
// Use an explicit SqlParameter.
foreach (string name in context.ExecuteStoreQuery<string>
("Select Name from Department where DepartmentID < @p0",
new SqlParameter { ParameterName = "p0", Value = 5 }))
{
Console.WriteLine(name);
}
}
public class DepartmentInfo
{
private DateTime _startDate;
private String _name;
private Int32 _departmentID;
public Int32 DepartmentID
{
get
{
return _departmentID;
}
set
{
_departmentID = value;
}
}
public String Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public DateTime StartDate
{
get
{
return _startDate;
}
set
{
_startDate = value;
}
}
}
public static void ExecuteStoreCommands()
{
using (SchoolEntities context =
new SchoolEntities())
{
int DepartmentID = 21;
// Insert the row in the Department table. Use the parameter substitution pattern.
int rowsAffected = context.ExecuteStoreCommand("insert Department values ({0}, {1}, {2}, {3}, {4})",
DepartmentID, "Engineering", 350000.00, "2009-09-01", 2);
Console.WriteLine("Number of affected rows: {0}", rowsAffected);
// Get the DepartmentTest object.
DepartmentInfo department = context.ExecuteStoreQuery<DepartmentInfo>
("select * from Department where DepartmentID= {0}", DepartmentID).FirstOrDefault();
Console.WriteLine("ID: {0}, Name: {1} ", department.DepartmentID, department.Name);
rowsAffected = context.ExecuteStoreCommand("delete from Department where DepartmentID = {0}", DepartmentID);
Console.WriteLine("Number of affected rows: {0}", rowsAffected);
}
}