如果我有Company
个对象:
var companies = db.Companies.Where(...);
还有与User
对象Company
相关的one-to-many
对象:
var users = db.Users.Where(...);
我如何达到select * from users where user.company in (company)
这样的标准
从一些文章中读过,我尝试过类似的内容:
users.Where(x => companies.Contains(x.company))
但是似乎不起作用。我在这里错过了什么?
编辑
确切答案:
public PartialViewResult IndexGrid(String search)
{
var companies = db.Users.Find(User.Identity.GetUserId()).Companies.AsQueryable();
Guid[] guids = companies.Select(c => c.Id).ToArray();
if (String.IsNullOrEmpty(search))
return PartialView("_IndexGrid", db.Set<Quotation>().OrderByDescending(x => x.Code).AsQueryable()
.Where(x => guids.Contains(x.Company.Id)));
else
return PartialView("_IndexGrid", db.Set<Quotation>().OrderByDescending(x => x.Code).AsQueryable()
.Where(x => guids.Contains(x.Company.Id))
.Where(x => x.Code.Contains(search)|| x.MasterCustomer.Name.Contains(search)));
}
答案 0 :(得分:5)
将最后一个变体用作
users.Where(x => companies.Contains(x.company))
.Net不知道如何比较公司,并且使用引用来引用相等的对象。 如果您的公司具有ID财产,请尝试此操作。如果没有,请告诉我。
users.Where(x => companies.Select(c => c.Id).Contains(x.company.Id))
答案 1 :(得分:1)
我想您需要选择其ID:
var companies = db.Companies.Where(...);
var myUsers = db.Users.Where(w=>companies.Select(x=>x.Id).Contains(w.CompanyId)).ToList();
如果两者之间都有参考,则可以例如:
var myUsers = db.Users.Include(x=>x.Company)
.Where(w=>w.Company != null && w.Company.Name == "MyCompanyName")
.ToList();