我正在制作一个ASP.NET C#库系统。 Het(MSSQL)数据库设计的截图:
要显示图书,请使用“租借”表格。 但是我的问题:
我现在的查询是:
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吗?)
答案 0 :(得分:2)
您可以按书名对书籍进行分组,然后从每个组中选择第一项。这是如何模拟“不同”的巧妙方法。在您的情况下将是
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();