我有一个名为Blog的模型
public class Blog
{
[Key]
public int blogId { get; set; }
[Required]
public string blogTitle { get; set; }
public string imagePath { get; set; }
[Required, DataType(DataType.Html)]
public string blogDescription { get; set; }
[DataType(DataType.DateTime)]
public DateTime blogDateTime { get; set; }
[Required]
public bool isPublished { get; set; }
[Required]
public BlogCategory blogCategory { get; set; }
public List<Comments> blogComments { get; set; }
}
和另一个模型Comment
public class Comments
{
[Key]
public int authorId { get; set; }
[Required]
public string commentAuthor { get; set; }
[DataType(DataType.Date)]
public DateTime commentDate { get; set; }
public bool isHidden { get; set; }
[Required, DataType(DataType.EmailAddress)]
public string commentAuthorEmail { get; set; }
[Required]
public string commentDescription { get; set; }
public Blog Blog { get; set; }
}
在博客控制器中,我想访问所有评论,其中isHidden = false
我试过的是:
var blog = await _context.Blog
.Include(cat => cat.blogCategory)
.Include(comments => comments.blogComments.Any(c => !c.isHidden))
.FirstOrDefaultAsync(m => m.blogId == id);
但我得到的唯一例外是
An unhandled exception occurred while processing the request.
InvalidOperationException: The Include property lambda expression 'comments => comments.blogComments.Find(c => Not(c.isHidden))' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.
我该如何解决这个问题?
发布于 2019-05-28 18:06:59
您无法在EF核心的Include
中进行过滤,请尝试使用以下代码
var blog = await _context.Blog
.Include(cat => cat.blogCategory)
.Include(comments => comments.blogComments)
.FirstOrDefaultAsync(m => m.blogId == id);
blog.blogComments = blog.blogComments.Where(b => b.isHidden == false).ToList();
发布于 2019-05-28 02:32:32
var blog = await _context.Blog
.Include(cat => cat.blogCategory)
.Include(comments => comments.blogComments)
.Select(x=> {
x.blogCategory = x.blogCategory;
x.blogComments = x.blogComments.Where(y=>!y.IsHidden)
})
.FirstOrDefaultAsync(m => m.blogId == id);
因为它是一个IQueryable,所以结果是一样的。它将只返回隐藏了博客评论的评论。这是考虑到你想要返回所有的博客,而不仅仅是那些隐藏评论的博客。
发布于 2019-05-28 20:59:40
您必须使用实体框架投影。
var blog = await _context.Blog
.Select(p => new Blog
{
blogComments = p.blogComments.Where(s => !s.isHidden )
}.FirstOrDefaultAsync(m => m.blogId == id);
https://stackoverflow.com/questions/56329521
复制相似问题