.net - 是否可以使 LinQ "understand"成为经典的 SQL 查询?

标签 .net sql linq linq-to-sql

是否可以让 LinQ to SQL 读取和理解如下所示的纯 SQL 查询?

SELECT * from myTable

我的老板要求我直接将纯 SQL 查询写入某个表中的数据库,并且该表将有一个名为“typeOfSelect”的字段,例如。

并且,在我的应用程序中,我将必须读取“typeOfSelect”字段并让 LinQ 理解这意味着什么。

谢谢!

最佳答案

您可以在 DataContext 上使用 ExecuteCommand 和 ExecuteQuery 方法。

var db = new MyDataContext();
IEnumerable<Table1> result = db.ExecuteQuery<Table1>("SELECT * FROM Table1");
db.ExecuteCommand("UPDATE Tabel1 SET Column1 = 'Foo'");

ExecuteQuery 将处理任何具有与表的列名匹配的属性名的对象。 ExecuteCommand 用于不返回结果集的 SQL 命令。

另一种方法是在将返回 DbCommand 对象的 DataContext 上使用 Connection.CreateCommand() 方法。然后,您只需使用要执行的 SQL 设置 CommandText 属性即可。

DbCommand command = myDataContext.Connection.CreateCommand();
command.CommandText = "SELECT * FROM Table1";

try {
    command.Connection.Open();
    DbDataReader reader = command.ExecuteReader();
    // do something usefull with the reader like creating a DataTable
} finally {
    command.Connection.Close();
    command.Dispose();
}

你也可以看看这个MSDN一些其他示例的链接。

关于.net - 是否可以使 LinQ "understand"成为经典的 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/818643/

相关文章:

c# - 这种制作相对路径的方法会起作用吗?

c# - 如何在 ParameterStore aws .NET C# 中设置参数的过期时间?

sql - 全外连接

php - SQL 按案例排序错误

sql - 公共(public)表表达式有什么用?

c# - 使用 Htmlagilitypack + LINQ + Lambda 提取表

c# - 使用 LINQ to Entities 的时间跨度总和

c# - 带有非传递 IComparer 的 OrderBy

C# Regex 将 aabbccddeeff 匹配为两个 aabbcc 和 ddeeff 集

asp.net - 开发或部署 .NET 应用程序是否需要付费?