我尝试使用ViewModel在视图中显示存储在数据库中的一些平均值。一切顺利,直到我尝试检索孙表中的值。
模型如下所示:Library model
ViewModel:
public string Firstname { get; set; }
public int NumberOfBooks { get; set; }
public double AvgScore { get; set; }
public double BookPeopleAvg { get; set; }
public double AvidReadersAvg { get; set; }
public double LibraryinternalAvg { get; set; }
这是控制器动作:
public async Task<ActionResult> Index()
{
var authors = db.Authors
.Include(g => g.Books)
.Include(g => g.Books.Select(c => c.Reviews))
.Select(g => new AuthorViewModel
{
Firstname = g.Firstname,
NumberOfBooks = g.Books.Count(),
AvgScore = g.Books.Average(c => (double?)c.Score) ?? 0,
BookPeopleAvg = g.Books.Select(c => c.Reviews.Average(x => (double?)x.BookPeople) ?? 0)
});
return View(await authors.ToListAsync());
}
我能够很好地获得AvgScore,但是获得BookPeopleAvg(以及其他两个)的平均值对我来说很难。我使用GroupBy找到了一些答案,但我无法将它们编入我的查询中。
我为BookPeopleAvg获取的编译错误是:
CS0029无法隐式转换类型&#39; System.Collections.Generic.IEnumerable&#39;到&#39;加倍&#39;
我尝试了一些不同的演员虽然我不认为问题在于转换,尽管错误信息暗示如此。
答案 0 :(得分:0)
更改此
BookPeopleAvg = g.Books.Select(c => c.Reviews.Average(x => (double?)x.BookPeople) ?? 0)
到这个
BookPeopleAvg = g.Books.SelectMany(c => c.Reviews).Average(x => (double?)x.BookPeople) ?? 0)
你这样做的方式你实际上是在选择一个IEnumerable的双打(你的平均值)