简体   繁体   English

根据子对象字段值获取父对象

[英]Get parent objects based on child object field value

I need to return all objects that have child objects with a certain field != null. 我需要返回所有带有带有特定字段!= null的子对象的对象。

NOTE: EpicStoryId is nullable int (as in 'int?') 注意: EpicStoryId是可为null的int(如在'int?'中一样)

I have tried: 我努力了:

return _context.Features
            .Where(x => x.UserStories.Any(us => us.EpicStoryId.HasValue) 
                && x.Id == Id)
            .FirstOrDefault();

and I have tried: 我已经尝试过:

return _context.Features
            .Where(x => x.UserStories.Any(us => us.EpicStoryId != null) 
                && x.Id == Id)
            .FirstOrDefault();

and for good measure: 并采取以下措施:

return _context.Features
            .Where(x => x.UserStories.Any(us => us.EpicStoryId.HasValue == false) 
                && x.Id == Id)
            .FirstOrDefault();

and finally: 最后:

return _context.Features
            .Where(x => x.UserStories.Any(us => us.EpicStoryId > 0) 
                && x.Id == Id)
            .FirstOrDefault();

But none of these work. 但是这些都不起作用。 It's still returning every 'Feature' with Id=Id regardless if a child has a value for EpicStoryId or not. 不管子对象是否具有EpicStoryId值,它仍会返回带有Id=Id每个“功能”。 (FYI, I checked the data and there ARE null values for some EpicStoryId 's.) (仅供参考,我检查了数据,并且某些EpicStoryId的值为空。)

sample data: 样本数据:

在此处输入图片说明

Any will return true i any 1 EpicStoryId has value so your your condition is failing. Any任何1 EpicStoryId具有值,则Any将返回true,因此您的条件失败。

All should do:- All应该做的:

return _context.Features
               .FirstOrDefault(x => x.UserStories.All(us => us.EpicStoryId.HasValue) 
                    && x.Id == Id);

If you need to return all objects then don't use FirstOrDefault() , use combination of .Where() and .ToList() methods : 如果需要返回所有对象,则不要使用FirstOrDefault() ,请结合使用.Where().ToList()方法:

For any of us EpicStoryIds are not null use : 对于我们中的任何一个EpicStoryIds都不为null,请使用:

return _context.Features
            .Where(x => x.Id == Id && x.UserStories.Any(us => us.EpicStoryId.HasValue))
            .ToList();

For all of us EpicStoryIds are not null you can use : 对于我们所有人来说,EpicStoryIds都不为空,您可以使用:

return _context.Features
            .Where(x => x.Id == Id && x.UserStories.All(us => us.EpicStoryId.HasValue))
            .ToList();

If you want to return list of UserStories and not Features , you can use : 如果要返回UserStories列表而不是Features ,可以使用:

return _context.Features
            .Where(x => x.Id == Id)
            .SelectMany(x => x.UserStories
              .Where(us => us.EpicStoryId.HasValue))
            .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM