Good day I have this 2 models
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; }
}
and
public partial class Post
{
public Guid Id { get; set; }
public string Text { get; set; }
public int? User { get; set; }
public DateTime? DateCreated { get; set; }
}
and I want to join this 2 into this 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; }
}
and I have this join query
(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();
The problem is I don't know how to populate the List<Images>
in my result of the join statement.
Is there anyone have the idea on how to that value?
CodePudding user response:
You do not need JOIN to Photos. Just fill list in projection
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()
};