在entityframework中,我们可以使用ExecuteStoreQuery或ExecuteStoreCommand来执行sql查询。那么它们之间有什么区别(哪种情况不同)?
谢谢。
答案 0 :(得分:5)
<强> ExecuteStoredQuery 强>
直接针对返回的数据源执行查询 键入结果序列。
和MSDN
ExecuteStoreCommand
使用直接对数据源执行任意命令 现有的连接。
Example for ExecuteStoreQuery:
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);
}
}
Example for ExecuteStoreCommand
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);
}
}