gpt4 book ai didi

c# - ExecuteStoreQuery 和 ExecuteStoreCommand 有什么区别

转载 作者:太空狗 更新时间:2023-10-29 23:14:26 25 4
gpt4 key购买 nike

在entityframework中我们可以使用ExecuteStoreQuery或者ExecuteStoreCommand来执行sql查询。那么它们之间有什么区别(不同的场景)?

谢谢。

最佳答案

MSDN 的区别很明显

ExecuteStoredQuery

Executes a query directly against the data source that returns asequence of typed results.

MSDN

ExecuteStoreCommand

Executes an arbitrary command directly against the data source usingthe existing connection.

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);
}
}

关于c# - ExecuteStoreQuery 和 ExecuteStoreCommand 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25793027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com