一些背景
我想将对象列表(我的模型视图)绑定到网格。模型视图包含特定实体和来自已连接实体的字段的字段。
由于dbContext超出范围,我尝试绑定时遇到错误。我意识到我需要使用.Include()方法来急切加载我的导航属性。但是,我怀疑,因为我使用Linq to Entities,我现在又生成了另一个错误:
“无法转换类型'System.Linq.IQueryable 1' to type 'System.Data.Objects.ObjectQuery
1'.LINQ to Entities仅支持转换EDM原语或枚举类型。”
我的代码如下所示,我在这里需要做什么的想法?
提前致谢!
public static List<PlanViewModel> GetPlans()
{
using (var context = new RepEntities())
{
var query = (from p in context.Plans
join r in context.RealEstateDetails on p.ReId equals r.ReId
select new PlanViewModel
{
PlanName = p.PlanName,
TargetCompletionDate = p.TargetCompletionDate,
ActualCompletionDate = p.ActualCompletionDate,
Provision = p.Provision,
StatusTypeId = p.StatusTypeId,
StatusCommon = p.StatusCommon,
Building = r.BuildingName,
City = r.City,
Country = r.Country
}).Include("StatusCommon");
return query.ToList();
}
}
答案 0 :(得分:2)
你几乎就在那里,只需在Include("StatusCommon")
之后立即context.Plans
。因为您需要在迭代之前包含StatusCommon,所以这样您就可以为每次迭代设置StatusCommon值。
public static List<PlanViewModel> GetPlans()
{
using (var context = new RepEntities())
{
var query = (from p in context.Plans.Include("StatusCommon")
join r in context.RealEstateDetails on p.ReId equals r.ReId
select new PlanViewModel
{
PlanName = p.PlanName,
TargetCompletionDate = p.TargetCompletionDate,
ActualCompletionDate = p.ActualCompletionDate,
Provision = p.Provision,
StatusTypeId = p.StatusTypeId,
StatusCommon = p.StatusCommon,
Building = r.BuildingName,
City = r.City,
Country = r.Country
}).toList();
return query;
}
}