EF 4.1 LITTLE query

2012-01-14 linq entity-framework-4.1

I have this POCO and I want to return a list of the users in a particular company.

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

This is my LINQ query:

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

I have this compilation error on the second query:

Error 2 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable>' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)

I want to get a list of the users, similar to a plain SQL statement like

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)

Thanks in advance.

Answers

Your user query could be:

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

This will return all users in any branch of the company.

It looks to me like you could just use:

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

I notice you have both Company and CompanyId on your Branch entity, though. That seems redundant, even though it simplifies this query slightly. You should be able to get rid of Branch.CompanyId and User.BranchId and just use the entity associations.

Related