gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:51:13 26 4
gpt4 key购买 nike

当我运行这行代码时

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.DbQuery1[ClassLibrary1.Company]' to type 'System.Data.Entity.DbSet1[ClassLibrary1.Company]'.

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

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

谢谢。

最佳答案

试试这个

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

关于linq - C# Entity Framework 4.1 : include paths in query for loading related objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7850579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com