Asp.net mvc 使用LINQ查看多个表MVC5中的数据

Asp.net mvc 使用LINQ查看多个表MVC5中的数据,asp.net-mvc,linq,mvvm,Asp.net Mvc,Linq,Mvvm,我有下面两张桌子 public class Book { public int Id { get; set; } [Required] [StringLength(255)] public string BookTitle { get; set; } [Required] [StringLength(255)] public string Author { get; set; } [Required] [StringL

我有下面两张桌子

public class Book
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string BookTitle { get; set; }

    [Required]
    [StringLength(255)]
    public string Author { get; set; }

    [Required]
    [StringLength(400)]
    public string Description { get; set; }
}
以及

一本书可以有很多评级。我需要写一个查询以便 我可以查看每本书的书名、作者、描述和平均评分。我知道我可以使用视图模型,但我不知道如何构造 LINQ查询


希望您能提供帮助

一种方法是在
书籍
上设置导航属性:

public class Book
{
    public ICollection<Rating> Ratings { get; set; }
}

如果使用实体框架中的
DbContext
,这将转换为SQL查询。

一种方法是在
书籍
上设置导航属性:

public class Book
{
    public ICollection<Rating> Ratings { get; set; }
}

如果使用实体框架中的
DbContext
,这将转换为SQL查询。

让我们先介绍一个viewModel类:

public class BookViewModel
{
    public string BookTitle { get; set; }
    public string Author { get; set; }
    public string Description { get; set; }
    public double AvgRating { get; set; }
}
然后我们可以执行以下LINQ

var bookViewModels = context.Books.GroupJoin(context.Ratings, x => x.Id, y => y.BookId, 
    (book, rates) => new BookViewModel
{
    Author = book.Author,
    BookTitle = book.BookTitle,
    Description = book.Description,
    AvgRating = rates.Average(r => r.Rate)
});

书籍
类中设置
评级
导航属性可能会更容易。

让我们先介绍一个viewModel类:

public class BookViewModel
{
    public string BookTitle { get; set; }
    public string Author { get; set; }
    public string Description { get; set; }
    public double AvgRating { get; set; }
}
然后我们可以执行以下LINQ

var bookViewModels = context.Books.GroupJoin(context.Ratings, x => x.Id, y => y.BookId, 
    (book, rates) => new BookViewModel
{
    Author = book.Author,
    BookTitle = book.BookTitle,
    Description = book.Description,
    AvgRating = rates.Average(r => r.Rate)
});

书籍
类中设置
评级
导航属性可能会更容易。

非常感谢!效果很好。输出如预期。非常感谢!效果很好。产出如预期。