當我運行從這個方法這行代碼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