我試圖帶回一個對象列表。該對象具有第二個類的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