如果我有这个 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/