我有這個POCO,我想返回特定公司的用戶列表。EF 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>' 改爲'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)
感謝。
值得一提的是,您的SQL查詢可以簡化爲:'選擇dbo.Users * FROM分行 INNER JOIN dbo.Users ON dbo.Branches.BranchId = dbo.Users.BranchId WHERE dbo.Branches.CompanyId = 8 「你根本不需要加入公司。 – 2012-01-13 18:46:58