简体   繁体   English

WHERE IN子句AS对象实体框架

[英]WHERE IN clause AS object Entity Framework

If I have a Company objects : 如果我有一个Company对象:

var companies = db.Companies.Where(...);

And a User objects which related to Company object one-to-many : 而一个User ,其涉及到的对象Company对象one-to-many

var users = db.Users.Where(...);

How I can achieve a criteria like select * from users where user.company in (company) 我如何才能达到诸如select * from users where user.company in (company)的标准

Reading from some articles, I tried something like : 阅读一些文章,我尝试过类似的方法:

users.Where(x => companies.Contains(x.company))

But seems doesn't work. 但是似乎不起作用。 What I missed here? 我在这里错过了什么?

EDIT 编辑

Exact Answer : 确切答案:

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)));
}

When you use last variant as 当您将最后一个变体用作

users.Where(x => companies.Contains(x.company))

.Net doesn't know how to compare Companies and uses references to equal objects. .Net不知道如何比较公司,并使用对相等对象的引用。 Please, try this if your Company has id property. 如果您的公司具有ID财产,请尝试此操作。 If not, please let me know. 如果没有,请告诉我。

users.Where(x => companies.Select(c => c.Id).Contains(x.company.Id))

I guess you need to select for its IDs: 我想您需要为其ID选择:

var companies = db.Companies.Where(...);
var myUsers = db.Users.Where(w=>companies.Select(x=>x.Id).Contains(w.CompanyId)).ToList();

if you have a reference between them both, then you can for example: 如果两者之间都有参考,则可以例如:

var myUsers = db.Users.Include(x=>x.Company)
                   .Where(w=>w.Company != null && w.Company.Name == "MyCompanyName")
                   .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM