当我运行从这个方法这行代码C#实体框架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;
}
我得到这个错误:
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery
1[ClassLibrary1.Company]' to type 'System.Data.Entity.DbSet
1[ClassLibrary1.Company]'.
编译时我没有错误。在EF 4.0中,此代码运行正确,而不是DbSet <>,ObjectQuery <>。
我是EF 4.1的初学者,所以任何建议都会有用。
谢谢。
您不需要'AsQueryable'。它只会没有工作。 – Slauma
cadrell0,感谢您的答案,它适用于您的解决方案。 – Cargo