i have a linq query for fetch data from 3 table (Post, Category, Tag).
i want show latest posts (10 num) in default page of a blog: post title, post tags name and post category name, post short description. i type this linq query
List<Post> IBlogRepository.PostsForList(int pageNo, int pageSize)
{
using (var context = new MJBweblogContext())
{
IQueryable posts = from Post in context.Posts
where Post.Published == true
select new
{
Post.Title,
Post.ShortDescription,
Post.Description,
Post.MetaData,
Post.PostedOn,
Post.UrlSlug,
Post.Published,
Post.Modified,
Post.Category,
Post.Tags,
Post.Category.Name,
};
if (posts != null)
{
return posts.OfType<Post>() // i give error if i remove OfType<Post>()
.OrderByDescending(p => p.PostedOn)
.Skip(pageNo * pageSize)
.Take(pageSize)
.ToList();
}
else
{
return null;
}
}
}
but i have two problem:
if i remove OfType() VS2017 tell me:
Error CS0266 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) MJBweblog C:\\Users\\mjb\\source\\repos\\MJBweblog\\MJBweblog\\DAL\\BlogRepository.cs 44 Active
this is What I want to show for users in default page. (a list of this)
If your Post class is an entity class then you don't need to create another anonymous type with select. Below Linq chain should work for what you are trying to achieve. Also as per the comments - it is not a good practice to return null for a list, the caller can check the Count property to see if the list is empty.
using (var context = new MJBweblogContext())
{
return context.Posts.Where(post => post.Published)
.OrderByDescending(p => p.PostedOn)
.Skip(pageNo * pageSize)
.Take(pageSize)
.ToList();
}
You can't just skip all of that other stuff?
List<Post> IBlogRepository.PostsForList(int pageNo, int pageSize)
{
using (var context = new MJBweblogContext())
{
return context.Posts.Where(a => a.Published == true)
.OrderByDescending(p => p.PostedOn)
.Skip(pageNo * pageSize)
.Take(pageSize)
.ToList();
}
}
if you're not getting your category information, you should be able to use INCLUDE
List<Post> IBlogRepository.PostsForList(int pageNo, int pageSize)
{
using (var context = new MJBweblogContext())
{
return context.Posts.Include("Category").Where(a => a.Published == true)
.OrderByDescending(p => p.PostedOn)
.Skip(pageNo * pageSize)
.Take(pageSize)
.ToList();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.