我试图带回一个对象列表。该对象具有第二个类的IEnumerable属性。我试图根据条件过滤这个子列表。过滤IEnumerable子属性
有类:
public class Parent
{
public int Id { get; set; }
public string Title { get; set; }
public bool Active { get; set; }
public virtual IEnumerable<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Title { get; set; }
public int ParentId { get; set; }
public int OtherId { get; set; }
public bool Active { get; set; }
public virtual Parent Parent { get; set; }
}
这里就是我试图让家长和筛选孩子的EF代码:
public IEnumerable<ParentViewModel> GetParents(int otherId)
{
var parents = _databaseContext.Parents
.Include(i => i.Children.Where(child => child.OtherId == otherId));
return parents;
}
当我把这种方法,我得到一个ArgumentException,消息:
The Include path expression must refer to a navigation property defined on the type.
Use dotted paths for reference navigation properties and the Select operator for
collection navigation properties.
鉴于异常提到使用Select,我已经tr IED这样做太:
public IEnumerable<ParentViewModel> GetParents(int otherId)
{
var parents = _databaseContext.Parents
.Where(parent => parent.Active == true)
.Include(parent => parent.Children);
.Select(parent => new
{
Active = parent.Active,
Id = parent.Id,
Children = parent.Children
.Where(child => child.OtherId == propertyId)
.Select(child => new
{
Active = child.Active,
Id = child.Id,
ParentId = child.ParentId,
OtherId = child.OtherId,
Title = child.Title
},
Title = parent.Title
});
return parents;
}
这也吹了起来,让我有例外:
The specified type member 'Children' is not supported in LINQ to
Entities. Only initializers, entity members, and entity navigation
properties are supported.
而这正是我所有的想法!我不知道我在做什么错,但是这并不觉得它应该像以前一样艰难,所以我猜测我错过了Entity Framework的一些非常重要的东西。
对我来说,看起来你的子类不在你的实体模型中。所以EF无法将其转换为有效的Sql。 所以我看到两个选项: 将子表添加到模型并且您的查询应该工作或 在您的父母上调用.ToList(),然后您可以使用Linq2Objects进行查询。 – Dannydust
对不起,如果我不清楚,顶部的Parent和Child类是我的实体,所以Child作为IEnumerable在Parent上。除非你的意思是我没有得到的其他东西? –
您是否使用EF Code First或您是否从现有数据库生成模型? – Dannydust