我有一个名为Tag
的班级。每个标记都有一些News
,Article
和“轮询”。我想要Get All Related Post哪个有Tag。
为此,我使用此查询:
public Tag Get(string tagName, int page, int recordsPerPage = 10)
{
int skip = page * recordsPerPage;
return
_tags.Where(tag => tag.Title.ToLower() == tagName.ToLower()).Include(row => row.Articles
.OrderByDescending(n => n.Code).Skip(skip).Take(recordsPerPage).ToList())
.Include(row => row.News.AsQueryable()).OrderBy(news => news.Code).Skip(skip).Take(recordsPerPage)
.Include(row => row.Polls).OrderByDescending(poll => poll.Code).Skip(skip).Take(recordsPerPage).FirstOrDefault();
}
但是当我运行Project I时出现此错误:
Include路径表达式必须引用在类型上定义的导航属性。使用虚线路径作为参考导航属性,使用Select运算符作为集合导航属性。
答案 0 :(得分:0)
您不能将表达式传递给Include方法,该方法不是属性表达式,请查看代码
.Include(row => row.Articles.OrderByDescending(n => n.Code).Skip(skip).Take(recordsPerPage).ToList())
.Include(row => row.News.AsQueryable())
正如你所看到的,在include中,你正在调用许多方法,而且不允许这样做。
您必须为此更改:
.Include(row => row.Articles)
.Include(row => row.News)
让我尝试改进您的代码,您当前的代码是这样的:
_tags.Where(tag => tag.Title.ToLower() == tagName.ToLower()).Include(row => row.Articles
.OrderByDescending(n => n.Code).Skip(skip).Take(recordsPerPage).ToList())
.Include(row => row.News.AsQueryable()).OrderBy(news => news.Code).Skip(skip).Take(recordsPerPage)
.Include(row => row.Polls).OrderByDescending(poll => poll.Code).Skip(skip).Take(recordsPerPage).FirstOrDefault();
让我们在换行符中打破它
_tags.Where(tag => tag.Title.ToLower() == tagName.ToLower())
.Include(row => row.Articles.OrderByDescending(n => n.Code).Skip(skip).Take(recordsPerPage).ToList())
.Include(row => row.News.AsQueryable())
.OrderBy(news => news.Code)
.Skip(skip)
.Take(recordsPerPage)
.Include(row => row.Polls)
.OrderByDescending(poll => poll.Code)
.Skip(skip)
.Take(recordsPerPage)
.FirstOrDefault();
如果您只需要一个标记,则无需将此大方法链接起来,您可以使用此方法简化:
public Tag Get(string tagName, int page, int recordsPerPage = 10)
{
return _tags.Include(tag => row.Articles).Include(tag => row.News).Include(tag => row.Polls)
.OrderBy(tag => news.Code)
.FirstOrDefault(tag => tag.Title.ToLower() == tagName.ToLower());
}