C#:LINQ to SQL:执行文字查询

标签 c# sql linq-to-sql

如果我有这个 SQL 查询:

“按 PostedDateTimeUtc desc 从发布订单中选择不同的前 1 个 'PostId' = isnull(RootPost,Id), PostedDateTimeUtc”

我需要使用 DataContext 枚举结果。也就是说,如何将这条 SQL 发送到 DataContext 并解析结果?

我该怎么做?匿名返回结果的方法会是什么样子?

最佳答案

要执行将从已知实体返回结果的 SQL 查询,您可以使用 DataContext.ExecuteQuery方法:

IEnumerable<Post> = dataContext.ExecuteQuery<Post>(sqlQuery);

对于自定义结果集,Execute 方法无法推断和创建匿名类型,但您仍然可以创建一个类,其中包含在自定义 SQL 查询中选择的字段。

class CustomPostResult  // custom type for the results
{
    public int? PostId { get; set; }
    public DateTime PostedDateUtcTime { get; set; }
}

//...

string sqlQuery = @"SELECT DISTINCT TOP 1 'PostId' = ISNULL(RootPost,Id),
                   PostedDateTimeUtc FROM Post ORDER BY PostedDateTimeUtc DESC";

IEnumerable<CustomPostResult> = dataContext.
                                        ExecuteQuery<CustomPostResult>(sqlQuery);

查看这篇文章:

关于C#:LINQ to SQL:执行文字查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1151284/

相关文章:

c# - C# 窗体中的点击

sql - 查找唯一的天数

mysql连接2个表,2列

c# - 在 C# 中的 linq-sql 连接查询上有多个 Id

c# - 无法创建类型为 'Anonymous type' 的常量值。在此上下文中仅支持原始类型或枚举类型

c# - 将 RTF 字符串转换为 XAML 字符串

c# - EF Core 2.0 - 包含和 ThenInclude : child collection -- grandchild collection

c# - 需要帮助来逆转此 Lambda 操作的逻辑

sql - SSIS:需要在其他SQL查询中使用SQL查询结果来获取数据

c# - 如果我进行计数,Linq 会首先检索所有记录吗?