代码之家  ›  专栏  ›  技术社区  ›  core

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

  •  2
  • core  · 技术社区  · 17 年前

    如果我有这个SQL查询:

    “从PostedDateTimeUtc desc的邮政订单中选择不同的前1个'PostId'=isnull(RootPost,Id),PostedDateTime Utc”

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

    3 回复  |  直到 17 年前
        1
  •  4
  •   Christian C. Salvadó    17 年前

    为了执行将从已知实体返回结果的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);
    

    查看这篇文章:

        2
  •  0
  •   hunter    17 年前

    我通常将结果转储到列表<>您正在使用的LINQ对象。

    List<Post> posts = new List<Post>();
    
    using(your datacontext)
    {
      var result = // Your query
      posts = result.ToList():
    }
    
    return posts;  
    
        3
  •  0
  •   Sergey Sergey    17 年前

    您可以尝试使用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);
    

    我还没有真正运行过这个,所以如果有人发现问题,我会解决的。