オブジェクトのリストを取り戻そうとしています。このオブジェクトには、2 番目のクラスの 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.
そして、それは私がすべてのアイデアを失っているところです!何が間違っているのかわかりませんが、これまでほど難しいとは思わないので、Entity Framework のかなり基本的なものが欠けていると思います。