选择Linq to Entities查询中的第一项

时间:2014-05-02 13:18:25

标签: c# linq linq-to-entities

我有以下代码:

  context.Posts
    .SelectMany(x => x.Packs
      .SelectMany(y => y.Files, (y, z) => new {
        File = new { Key = z.Key }
      })        
      .Select(y => new PostModel {
        Id = x.Id,
        File = y.File.Key,
        Types = x.Types
      })
    ).ToList();

这是有效的,但有一个帖子有很多PostLocalized。

我想在我的查询中选择PostLocalized哪个.Culture == culture。

我需要使用其数据来创建PostModel。类似的东西:

  context.Posts
    // PICK the first PostLocalized which .Culture property equals culture 
    .SelectMany(x => x.Packs
      .SelectMany(y => y.Files, (y, z) => new {
        File = new { Key = z.Key }
      })        
      .Select(y => new PostModel {
        Id = x.Id,
        File = y.File.Key,
        Types = x.Types,
        //Title = PostLocalized.Title,
        //Body = PostLocalized.Body
      })
    ).ToList();

我该怎么做?

注意:

Post和PostLocalized实体如下:

public class Post {
  public Int32 Id { get; set; }
  public Boolean Active { get; set; }
  public PostTypes Types { get; set; }

  public virtual ICollection<PostLocalized> PostsLocalized { get; set; }
} // Post

public class PostLocalized {

  public Int32 Id { get; set; }
  public String Culture { get; set; }
  public String Body { get; set; }
  public String Title { get; set; }

  public virtual Post Post { get; set; }
  public virtual ICollection<Pack> Packs { get; set; }

} // PostLocalized

public class Pack {
  public Int32 Id { get; set; }
  public Boolean Active { get; set; }
  public DataType Type { get; set; }
  public DateTime Updated { get; set; }

  public virtual ICollection<File> Files { get; set; }
  public virtual ICollection<PostLocalized> PostsLocalized { get; set; }    
} // Pack

public class File {
  public Int32 Id { get; set; }
  public Byte[] Data { get; set; }
  public Guid Key { get; set; }
  public String Mime { get; set; }
  public virtual Pack Pack { get; set; }
} // File

谢谢你, 米格尔

1 个答案:

答案 0 :(得分:1)

这本身并不完美或高效,但它至少应该起作用,并且查询优化器有望使它快速。

context.Posts
       .SelectMany(post => post.Packs
       .SelectMany(pack => pack.Files
       .Select(file => new PostModel
                       {
                          Id = post.Id,
                          File = file.Key,
                          Types = post.Types,
                          Title = post.PostsLocalized.First(pl => pl.Culture == culture).Title,
                          Body = post.PostsLocalized.First(pl => pl.Culture == culture).Body
                       })))
       .ToList();