Search code examples
linqentity-framework-4.1

C# Entity Framework 4.1: include paths in query for loading related objects


When I run this line of code

queryCompanies = (DbSet)queryCompanies.Include(path);

from this method:

     public Company GetCompanyById(int companyId)
     {
        List<string> includePaths = new List<string>();
        includePaths.Add("Addresses");
        includePaths.Add("Users");
        Company company = null;
        using (Entities dbContext = new Entities())
        {   
            var queryCompanies = dbContext.Companies;

            if (includePaths != null)
            {
                foreach (string path in includePaths)
                    queryCompanies = (DbSet<Company>)queryCompanies.Include(path);
            }

                company = (from c in queryCompanies
                           where c.Id.Equals(companyId)
                           select c).FirstOrDefault<Company>();
        }
        return company;
     }

I get this error:

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery1[ClassLibrary1.Company]' to type 'System.Data.Entity.DbSet1[ClassLibrary1.Company]'.

At compilation I have no error. In EF 4.0 this code runs correct using instead of DbSet<>, ObjectQuery<>.

I am a beginner in EF 4.1 so any suggestion will be useful.

Thanks.


Solution

  • Try this

     public Company GetCompanyById(int companyId)
     {
        List<string> includePaths = new List<string>();
        includePaths.Add("Addresses");
        includePaths.Add("Users");
        Company company = null;
        using (Entities dbContext = new Entities())
        {   
            var queryCompanies = dbContext.Companies.AsQueryable();
    
            if (includePaths != null)
            {
                foreach (string path in includePaths)
                    queryCompanies = queryCompanies.Include(path);
            }
    
                company = (from c in queryCompanies
                           where c.Id.Equals(companyId)
                           select c).FirstOrDefault<Company>();
        }
        return company;
     }