C# Entity Framework 4.1:在查询中包含路径以加载相关对象

Car*_*rgo 2 linq entity-framework-4.1

当我运行这行代码时

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

从这个方法:

     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;
     }
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

无法转换类型为“System.Data.Entity.Infrastructure.DbQuery 1[ClassLibrary1.Company]' to type 'System.Data.Entity.DbSet1[ClassLibrary1.Company]”的对象。

在编译时我没有错误。在 EF 4.0 中,此代码使用而不是 DbSet<>、ObjectQuery<> 正确运行。

我是 EF 4.1 的初学者,所以任何建议都会有用。

谢谢。

cad*_*ll0 5

尝试这个

 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;
 }
Run Code Online (Sandbox Code Playgroud)