过滤IEnumerable子属性

时间:2013-10-10 13:21:21

标签: c# entity-framework ef-code-first entity-framework-5 automapper

我正试图带回一个对象列表。此对象具有第二个类的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,我也尝试过这样做:

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.

这就是我完全没有想法的地方!我不知道我做错了什么,但这并不觉得它应该像以前一样难,所以我猜我错过了一些非常重要的实体框架。

1 个答案:

答案 0 :(得分:0)

啊,好的!我不熟悉Code First(我在我的项目中使用生成的模型),但我很确定EF不会认识到这些实体是相关的。错误消息:“...支持实体导航属性”告诉我您应该定义导航属性(这些实体之间的关系)。

public class Parent
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public bool Active { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    [Key]
    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 int ParentId [get;set;}
    [ForeignKey("ParentId")]
    public virtual Parent Parent { get; set; }
}