Issue
I want to display the last 4 articles of the last site on the main page in a concise way. I have made a model view and I only have a problem with ef core.
ViewModel:
public class ShowBlogForHomePageViewModel
{
public int BlogId { get; set; }
public string BlogTitle { get; set; }
public string BlogUrl { get; set; }
public string BlogImageName { get; set; }
public string MetaDescriptionBlog { get; set; }
}
IBlogService:
List<ShowBlogForHomePageViewModel> GetBlogPostForHome();
BlogService:
public List<ShowBlogForHomePageViewModel> GetBlogPostForHome()
{
var ListBlogs= _context.Blogs.OrderByDescending(b => new ShowBlogForHomePageViewModel()
{
BlogId = b.BlogId,
BlogImageName = b.BlogImageName,
BlogTitle = b.BlogTitle,
MetaDescriptionBlog = b.MetaDescriptionBlog,
BlogUrl = b.BlogUrl
}).Take(4).ToList();
return null;
}
I think this part is true . please check it:
public List<ShowBlogForHomePageViewModel> GetBlogPostForHome()
{
return _context.Blogs.OrderBy(b=>b.BlogId).Select(b => new ShowBlogForHomePageViewModel()
{
BlogId = b.BlogId,
BlogImageName = b.BlogImageName,
BlogTitle = b.BlogTitle,
MetaDescriptionBlog = b.MetaDescriptionBlog,
BlogUrl = b.BlogTitle
}).TakeLast(4).ToList();
}
Solution
try this
public List<ShowBlogForHomePageViewModel> GetBlogPostForHome()
{
return _context.Blogs
.OrderByDescending(b => b.BlogId)
.Select(b => new ShowBlogForHomePageViewModel
{
BlogId = b.BlogId,
BlogImageName = b.BlogImageName,
BlogTitle = b.BlogTitle,
MetaDescriptionBlog = b.MetaDescriptionBlog,
BlogUrl = b.BlogUrl
}).Take(4)
.ToList();
}
Answered By – Serge
Answer Checked By – Mildred Charles (BugsFixing Admin)