使用ICollection进行LINQ连接查询

时间:2015-04-02 09:21:08

标签: c# linq

我有以下课程:

 public partial class Person : ModificationEntity
{
    public Person()
    {
        this.PersonCompanies = new List<PersonCompany>();
    }

    public System.Guid PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }

    public virtual ICollection<PersonCompany> PersonCompanies { get; set; }
}

public partial class PersonCompany : ModificationEntity
{
    public System.Guid PersonCompanyId { get; set; }
    public System.Guid PersonId { get; set; }
    public System.Guid CompanyId { get; set; }

    public virtual Company Company { get; set; }
    public virtual Person Person { get; set; }
}

我需要查询给定公司名单的所有用户(List lstCompanyIds)。

所以我使用以下查询获取所有PersonCompanyId:

var qpc = (from c in lstCompanyIds
           join u in personCompanyService.GetPersonCompanies()
           on c equals u.CompanyId
           select u.PersonCompanyId).AsQueryable();

通过此查询,我想获得用户:

var query = from q in GetUsers()
             join q2 in qpc
             on q.PersonCompanies.Select(y => y.PersonCompanyId) equals q2
             select q;

但这会产生编译错误“join子句中某个表达式的类型不正确。在对'Join'的调用中类型推断失败。” 显然是因为我试图选择人员公司的集合。但是我该怎么做呢? (包含不起作用,因为我有两个要比较的集合......)

2 个答案:

答案 0 :(得分:1)

这里的问题是您要将IQueryable<Guid>Guid进行比较。如果我理解正确,那就是你想要实现的目标:

IQueryable<Guid> companyIds = Enumerable.Empty<Guid>().AsQueryable(); //qpc in your question
IQueryable<Person> persons = Enumerable.Empty<Person>().AsQueryable(); //q in your question
var result = persons.Where(person => person.PersonCompanies
            .Any(company => companyIds.Contains(company.CompanyId)));

答案 1 :(得分:1)

你能试试吗

    var qpc = (from res in
                      (from c in lstCompanyIds
                       join u in personCompanyService.GetPersonCompanies()
                       on c equals u.CompanyId
                       select u.PersonCompanyId)
                   join u in GetUser()
                  on res equals u.UserId
                  select u).AsQueryable();

我认为这应该有用

确保您要比较的所有ID都是System.Guid

类型