【问题标题】:LINQ query join only last valueLINQ 查询仅连接最后一个值
【发布时间】:2013-11-29 15:02:01
【问题描述】:

我正在制作一个 ASP.NET C# 库系统。 Het(MSSQL)数据库设计的屏幕截图:

为了展示书籍,我使用了 Rentals 表。 但是有我的问题

  • 我离开加入 Books 表和 Rentals 表(因为还需要显示还没有租过一次的书(参见 ID 为 3 的书
  • 当我刚刚离开时,我在我的书籍概览中看到我的书籍多次偏离...
  • SO:我应该需要一个 LINQ 查询来将 Books 与 Rentals 连接起来,但如果书籍已经被多次租用,他应该只 joinlast 值在那个 book_id 的表中
  • 看下图:查询应该只选择绿色选择的值...
  • (补充说明:如果有人租书,则返回值=0,如果他还书,则为1)

我现在的查询是:

var query = (from b in db.Books
                     join a in db.Authors on b.author_id equals a.author_id
                     join c in db.Categories on b.category_id equals c.category_id
                     join r in db.Rentals on b.book_id equals r.book_id into lf
                     from r in lf.DefaultIfEmpty()
                     select new BookDetails(
                                b.book_id,
                                b.title,
                                b.ISBN,
                                b.description,
                                b.author_id,
                                a.firstName,
                                a.lastName,
                                b.category_id,
                                r.returned == null ? 1 : r.returned)
                     ).ToList();

但就像我说的那样,这会显示我多次租借的书籍... 我一直在考虑“MAX”属性? (但这适用于 linq 吗?)

【问题讨论】:

    标签: c# asp.net sql-server linq join


    【解决方案1】:

    您可以按书籍 ID 对书籍进行分组,然后从每个组中选择第一项。这是模拟“不同”的一种巧妙方法。在你的情况下,那将是

    var query = (from b in db.Books
                 join a in db.Authors on b.author_id equals a.author_id
                 join c in db.Categories on b.category_id equals c.category_id
                 join r in db.Rentals on b.book_id equals r.book_id into lf
                 from r in lf.DefaultIfEmpty()
                 group new{ Book = b, Author = a, Rental = r }
                     by b.book_id into booksById
                 let item = booksById.First()
                 select new BookDetails(
                     item.Book.book_id,
                     item.Book.title,
                     item.Book.ISBN,
                     item.Book.description,
                     item.Book.author_id,
                     item.Author.firstName,
                     item.Author.lastName,
                     item.Book.category_id,
                     item.Rental.returned == null
                         ? 1 : item.Rental.returned))
                 .ToList();
    

    【讨论】:

    • 感谢您的帮助!如何在选择新 BookDetails 中找到“a”和“r”?他们已经不存在了……
    • 哦,你是对的,你必须将它们添加到聚合中。我将编辑我的答案。
    猜你喜欢
    • 2018-08-30
    • 2019-01-09
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    相关资源
    最近更新 更多