实体框架过滤器lambda导航属性

实体框架过滤器lambda导航属性

问题描述:

使用.NET实体框架6我需要过滤包含的虚拟集合的元素。我的意思是用以下代码很容易解释:

Using .NET Entity Framework 6 I need to filter the elements of an included virtual collection. What I mean is easily explained with the following code:

context.MyEntity.Include(navigationPropertyCollection => navigationPropertyCollection.Where(np => np.IsActive()))

代码只是一个例子,从MyEntity来说,我只想包含navigationPropertyCollection的活动元素。

the code code is just an example, to say from MyEntity I want include only active elements of navigationPropertyCollection.

有聪明的方法吗?


请注意,目前无法过滤哪些相关实体被加载。包含将始终引入所有相关实体。

Note that it is not currently possible to filter which related entities are loaded. Include will always bring in all related entities.

msdn参考

你可以尝试这个匿名投影

you could try this by anonymous projection

var resultObjectList = _context.
                   Parents.
                   Where(p => p.DeletedDate == null).
                   OrderBy(p => p.Name).
                   Select(p => new
                             {
                                 ParentItem = p,
                                 ChildItems = p.Children.Where(c => c.Name=="SampleName")
                             }).ToList();

类似在堆栈中回答