How to fetch records and group under each respective category in linq-to-sql or linq extension in Entity framework core 3.0 and project them into their respective DTOs?
I have the following DTOs
public class CategoryGalleryDto
{
public int Id { get; set; }
public string CategoryName { get; set; }
public List<ImageGalleryDto> ImagesList { get; set; }
}
public class ImageGalleryDto
{
public int Id { get; set; }
public string ImageName { get; set; }
public int CategoryId { get; set; }
}
I have the following records:
ImageGallery Table
Id ImageName CategoryId
1 image1 1
2 image2 1
4 image3 1
5 image1 2
6 image2 2
I want to have a list of categories and a list of its corresponding images with each category. How can I achieve that in linq? Please help, I'm really stuck with this.
ImageCategory Table
Id ImageCategory ImageDescription UploadedDate
1 Team Building Team Building Event 2020-05-11 00:00:00.000
2 Christmas Christmas Lunch 2020 2020-05-11 00:00:00.000
My code:
public List<CategoryGalleryDto> GetAllImages()
{
var imageList = new List<CategoryGalleryDto>();
try
{
var query = from p in _context.ImagesCategory
join s in _context.ImagesGallery on p.Id equals s.CategoryId into groupcat
from s in groupcat
select new { Categories = p.Id, Images = s };
var grouping = query.ToLookup(e => e.Categories);
}
catch (Exception ex)
{
throw ex;
}
return imageList;
}