[英]C#: LINQ to SQL: Executing literal query
如果我有此SQL查询:
“从发帖顺序中选择不同的前1个'PostId'= isull(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);
查看本文:
我通常将结果转储到您正在使用的LINQ对象的List <>中。
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);
我实际上还没有运行过,所以如果有人发现问题,我会解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.