LINQ 连接查询目标有列表字段

LINQ join query destination has List fields

美好的一天,我有这 2 个模型

public partial class PostPhoto
{
    public Guid Id { get; set; }
    public string Path { get; set; }
    public string Filename { get; set; }
    public int? User { get; set; }
    public Guid? Post { get; set; }
}

public partial class Post
{
    public Guid Id { get; set; }
    public string Text { get; set; }
    public int? User { get; set; }
    public DateTime? DateCreated { get; set; }
}

我想将这 2 个加入这个 ViewModel

public class PostViewModel
{
    public Guid Id { get; set; }
    [Required]
    public String PostBody { get; set; }
    public string Image { get; set; }
    public int UserId { get; set; }
    public string UserFullname { get; set; }
    public DateTime DateCreated { get; set; }

    public List<Images> ImageList { get; set; }
}

public class Images
{
    public string ImagePath { get; set; }

}

我有这个连接查询

(from post in _context.Post
                     join user in _context.AspNetUsers
                     on post.User equals user.Id
                     join photos in _context.PostPhoto
                     on post.Id equals photos.Post into phtos

                     orderby post.DateCreated descending

                     select new PostViewModel {
                         Id = post.Id,
                         UserId = user.Id,
                         UserFullname = string.Format("{0} {1}", user.Firstname, user.LastName),
                         PostBody = post.Text,
                         DateCreated = (DateTime)post.DateCreated,
                     }).ToList();

问题是我不知道如何在 join 语句的结果中填充 List<Images>。 有没有人知道如何获得该值?

您不需要加入照片。只需在投影中填写列表

var query = 
    from post in _context.Post
    join user in _context.AspNetUsers on post.User equals user.Id

    orderby post.DateCreated descending

    select new PostViewModel 
    {
        Id = post.Id,
        UserId = user.Id,
        UserFullname = string.Format("{0} {1}", user.Firstname, user.LastName),
        PostBody = post.Text,
        DateCreated = (DateTime)post.DateCreated,
        ImageList = _context.PostPhoto
            .Where(p => post.Id == p.Post)
            .Select(p => new Images { ImagePath = p.Path })
            .ToList()
    };