C#:LINQ到SQL:执行文字查询
问题描述:
如果我有这样的SQL查询:C#:LINQ到SQL:执行文字查询
“选择不同的顶部1 '帖子ID'= ISNULL(RootPost,ID),PostedDateTimeUtc从后为了通过PostedDateTimeUtc desc” 的
我需要用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);
检查这篇文章:
答
我通常的结果转储到您正在使用LINQ对象的名单<>。
List<Post> posts = new List<Post>();
using(your datacontext)
{
var result = // Your query
posts = result.ToList():
}
return posts;
答
你可以试试LINQ表达式。像这样的东西应该可能工作。
var results = (from post in dc.Posts
orderby post.PostedDateUtcTime descending
select new Post
{
RootPost = (post.RootPost == null) ? post.Id : post.RootPost
}).Distinct<Post>().Take<Post>(1);
我没有真的跑过这个,所以如果有人发现一个问题,我会解决这个问题。