简体   繁体   English

EF Core OrderBy 其他表上的引用计数

[英]EF Core OrderBy Count of References on other Table

I have a table with authors and a table with books.我有一张有作者的桌子和一张有书的桌子。

public class Author
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Book
{
    public int ID { get; set; }
    public string Name { get; set; }
    public Author Author { get; set; }
}

I want to order my Authors by the amount of Books they have.我想按他们拥有的书籍数量来订购我的作者。 I need to Access the data via _context.Authors.XXX as I have additional filtering applied on the IQueryable .我需要通过_context.Authors.XXX访问数据,因为我在IQueryable上应用了额外的过滤。

I am using net5.0 and ef core 5.0.我正在使用 net5.0 和 ef core 5.0。

Is there an 'elegant' way?有没有“优雅”的方式?

Thanks!谢谢!

Add a Books nav property and map accordingly, something named like:相应地添加Books nav 属性和 map,名称如下:

public ICollection<Book> Books { get; set; }

Then in your query:然后在您的查询中:

_context.Authors.OrderByDescending(x => x.Books.Count());

you need to update both your Author and Book classes.你需要更新你的 Author 和 Book 类。 The author class needs to include a navigational "Books" property which will hold a list of books by the Author, while the Book class will hold an AuthorId property which will serve as a foreign key to the Author table.作者 class 需要包含一个导航“Books”属性,该属性将包含作者的书籍列表,而 Book class 将包含一个 AuthorId 属性,该属性将用作 Author 表的外键。

public class Book
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string AuthorID {get; set; }
    public virtual Author Author { get; set; }
}

public class Author
{
    public Author() {
       this.Books = new List<Book>();
    }
    
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM