Domanda

I have the following code:

  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();

This is working but one Post has Many PostLocalized.

I would like to, in my query, pick the PostLocalized which .Culture == culture.

And I need to use its data to create the PostModel. something like:

  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();

How can I do this?

NOTE:

The Post and PostLocalized entities are the following:

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

Thank You, Miguel

È stato utile?

Soluzione

This is not exactly beautiful or efficient on its own but it should at least work and the query optimizer will hopefully make it fast.

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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top