gpt4 book ai didi

asp.net-mvc - 使用LINQ从多个表MVC5查看数据

转载 作者:行者123 更新时间:2023-12-03 11:03:32 24 4
gpt4 key购买 nike

我有以下两个表

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; }
}

和,
public class Rating
{
public int Id { get; set; }

[Required]
public int Rate { get; set; }

public Book Books { get; set; }

[Required]
public int BookId { get; set; }
}

一本书可以有很多等级。我需要写一个查询
我可以查看每本书的书名,作者,说明和平均评分。我知道我可以使用 View 模型,但是我不知道如何构造
LINQ查询

和帮助将不胜感激

最佳答案

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

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

然后,使用Linq,可以使用reference属性:
_context.Books.Select( c => new
{
c.BookTitle,
c.Author,
c.Description,
c.Ratings.Select( e => e.Rate ).Sum() / c.Ratings.Count()
});

如果使用Entity Framework中的 DbContext,它将转换为SQL查询。

关于asp.net-mvc - 使用LINQ从多个表MVC5查看数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42333904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com