您好我正在尝试将以下SQL语句转换为其LINQ等价物,因为我真的是.net(编码一天),我已经被困在这几个小时了。
self.tabBarController.tabBar.hidden=YES;
这是模型
SELECT *
FROM Books
WHERE BookID IN (SELECT BookID
FROM Borrows
WHERE UserID = 2)
我非常感谢任何人的帮助。
修改
上下文类
public class LibUser
{
[Key]
public int UserID { get; set; }
[Required, StringLength(50), Display(Name = "First Name")]
public string UserFirstName { get; set; }
[Required, StringLength(50), Display(Name = "Last Name")]
public string UserLastName { get; set; }
[Required, StringLength(10000), Display(Name = "Residence"), DataType(DataType.MultilineText)]
public string Adress { get; set; }
}
public class Book {
[Key]
public int BookID { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public DateTime Published{ get; set; }
}
public class Borrowed {
[Key]
public int BorrowID { get; set; }
public int UserID { get; set; }
public int BookID { get; set; }
}
答案 0 :(得分:3)
你可以这样做:
var Lnq = new LinqDataContext();
var borrowId = Lnq.Borrowed.Where(a => a.UserID == 2).Select(a => a.BookID).ToList();
var bookQuery = Lnq.Books.Where(a => borrowId.Contains(a.BookID))
.Select(a => a.YourColumn);
答案 1 :(得分:3)
假设您的上下文被称为db
,您可以执行以下查询
var borrowedBooksForUser = db.Books
.Where(b => db.Borrowed.Any(x => x.UserID == 2 && x.BookID == b.BookID));
答案 2 :(得分:3)
最好通过连接来执行此操作。
论点是:如果用户借阅了大量的书籍,或者数据中存在错误,那么您的子查询可能会返回大量ID,并且长列表中的SQL“IN”子句可能会变得非常慢。 / p>
使用联接:
SQL查询:
SELECT Books.* FROM Books
JOIN Borrows ON Borrows.BookID = Books.BookID
WHERE Borrows.UserID = 2
Linq声明:
var allBooksBorrowedByUser2 = db.Borrowed
.Where(borrow => borrow.UserID == 2)
.Join(db.Books,
borrow => borrow.BookID,
book => book.BookID,
(borrow, book) => book);
答案 3 :(得分:2)
导航会让一切变得更简单。
public class Borrowed {
[Key]
public int BorrowID { get; set; }
public int UserID { get; set; }
public int BookID { get; set; }
// Navigation Properties
public virtual LibUser User { get; set; }
public virtual Book Book { get; set; }
}
Borrows.Where(borrow => borrow.UserId == 2)
.Select(borrow => borrow.Book);
答案 4 :(得分:1)
试试这个,
var getResult=from b in db.Books
join bo in db.Borrows on b.BookID=bo.BookID
where bo.UserID=2