EF 4.1 POCO查询

时间:2012-01-13 18:23:12

标签: linq entity-framework-4.1

我有这个POCO,我想返回一个特定公司的用户列表。

public class Company
{
    public AccreditedCompany() 
    {
        this.Branches = new HashSet<Branch>();
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), ScaffoldColumn(false)]
    public int CompanyId { get; set; }
    public bool Active { get; set; } 

    public virtual ICollection<Branch> Branches { get; set; }         
}

public class Branch
{
    public Branch() 
    {
        this.Users = new HashSet<User>();
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), ScaffoldColumn(false)]
    public int BranchId { get; set; }
    public int CompanyId { get; set; }
    public string Name { get; set; }
    public string ContactName { get; set; }

    public virtual Company Company { get; set;}
    public virtual ICollection<User> Users { get; set; }  
}

public class User 
{

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), ScaffoldColumn(false)]
    public int UserId { get; set; }
    public int BranchId { get; set; }
    public string ComputerSN { get; set; }
    public string CameraSN { get; set; }

    public virtual Branch Branch { get; set; }         
}

这是我的LINQ查询:

var company = (from u in objDataContext.Companies.Include(c=>c.Branches.Select(v=>v.Users)) 
    where u.CompanyId == 8 select u).FirstOrDefault();

IQueryable<User> users = (from j in company.Branches select j.Users);

我在第二个查询中遇到此编译错误:

  

错误2无法隐式转换类型   'System.Collections.Generic.IEnumerable&GT;'   到'System.Linq.IQueryable'。存在显式转换(是   你错过了一个演员?)

我想获得一个用户列表,类似于像

这样的普通SQL语句
SELECT dbo.Users.* FROM Branches 
INNER JOIN dbo.Users ON dbo.Branches.BranchId = dbo.Users.BranchId 
INNER JOIN dbo.Companies ON dbo.Branches.CompanyId = dbo.Companies.CompanyId
WHERE     (dbo.Companies.CompanyId = 8)

提前致谢。

2 个答案:

答案 0 :(得分:3)

您的用户查询可能是:

IEnumerable<User> users = company.Branches.SelectMany(branch => branch.Users);

这将返回公司任何分支机构的所有用户。

答案 1 :(得分:0)

在我看来,你可以使用:

IQueryable<User> users = objDataContext.Users
                         .Where(u => u.Branch.CompanyId == 8);

我注意到您的Company实体上同时包含CompanyIdBranch。这似乎是多余的,即使它稍微简化了这个查询。你应该能够摆脱Branch.CompanyIdUser.BranchId,只使用实体关联。