混淆了如何将这个sql查询写入linq to sql
select FirstName from [User] where [UserId] in(
select LenderId from AffiliateLenderRelation where AffiliateId in (select Userid From [User] where [UserId] = 11)
)
到目前为止我尝试了什么
var innerquery = from iq in db.AffiliateLenderRelations where iq.AffiliateId == loggedInUser.UserId select iq.AffiliateId;
List<SelectListItem> lenders = db.Users
.Where(o => o.AccountTypeId == 1 && o.Deleted == false && innerquery.Contains(o.UserId))
.Select(o => new SelectListItem()
{
Value = o.UserId.ToString(),
Text = o.FirstName
}).ToList();
lenders.Insert(0, new SelectListItem() { Value = "0", Text = "All" });
答案 0 :(得分:1)
我认为不需要嵌套查询。您可以使用连接查询。试试这个
var lobj= (from u db.Users.where(x=>x.UserId==11)
let ces = from ce in db.AffiliateLenderRelation.where( y=> y.AccountTypeId == 1 && y.Deleted == false )
select ce.LenderId
where ces.Contains(u.UserID)
.Select(o => new SelectListItem()
{
Value = o.UserId.ToString(),
Text = o.FirstName
})).ToList();
答案 1 :(得分:1)
你的代码中的一切都很好,我猜只有一个错误。
将选择iq.AffiliateId更改为=&gt; iq.LenderId
var innerquery = from iq in db.AffiliateLenderRelations where iq.AffiliateId == loggedInUser.UserId select iq.AffiliateId;
List<SelectListItem> lenders = db.Users
.Where(o => o.AccountTypeId == 1 && o.Deleted == false && innerquery.Contains(o.UserId))
.Select(o => new SelectListItem()
{
Value = o.UserId.ToString(),
Text = o.FirstName
}).ToList();
lenders.Insert(0, new SelectListItem() { Value = "0", Text = "All" });