C# Linq to Entities:Nested SelectMany返回它想要的任何内容
我试图从我的域对象集中选择自定义类型,并注意到非常奇怪的EF行为。我完全可以弄清楚这一切发生的原因。因此,我:C# Linq to Entities:Nested SelectMany返回它想要的任何内容,c#,linq,entity-framework,linq-to-entities,C#,Linq,Entity Framework,Linq To Entities,我试图从我的域对象集中选择自定义类型,并注意到非常奇怪的EF行为。我完全可以弄清楚这一切发生的原因。因此,我: public class Person { public IList<Device> Devices { get; set; } } public class Device { public DeviceConfiguration DeviceConfiguration { get; set; } } public class DeviceC
public class Person
{
public IList<Device> Devices { get; set; }
}
public class Device
{
public DeviceConfiguration DeviceConfiguration { get; set; }
}
public class DeviceConfiguration
{
public IList<DeviceFeature> DeviceFeatures { get; set; }
}
public class DeviceFeature
{
public DeviceFeatureType DeviceFeatureType { get; set; }
}
问题在于,DeviceFeatures
填充了一些随机条目,即使该Person
没有任何设备
你知道为什么会这样吗
更新1:
我忘了提到的一件重要事情是,
personDTOs
之后被排序和分页(OrderBy,Skip,Take,ToList
),而这些“随机”设备功能仅包括在这之后。但如果我在这些操作之前选择了有问题的条目,我可以看到一切都如预期的那样。延迟执行和/或选择自定义类型可能有问题,但我无法理解进行此类选择的确切方式和正确方式请详细说明“随机条目”好吗?它们是设备
、空值
值的实例还是其他什么?@James it is DeviceFeature。DeviceFeature的单个记录无法与当前人员关联,因为此人没有任何设备。给定SelectMany
使用延迟执行,如果您调用ToList
,它是否为您提供了所需的内容?您可以发布生成的SQL吗?我会将您的解决方法写在下面,作为您自己的答案。也许EF开发团队的人会看到它并确认它是一个bug,或者有人会给出解释。(这将是我第一次在SQL Server的LINQ提供程序中看到错误。)但是,为了使问题能够为其他人重现,您正在使用的完整LINQ查询将非常有用-包括AsNoTracking
,OrderBy
,Skip
,Take
,等等。其中一个细节可能很重要。。。
var personDTOs = persons.Select(x =>
new PersonDTO
{
Devices = x.Devices,
DeviceFeatures = x.Devices.SelectMany(y => y.DeviceConfiguration.DeviceFeatures )
});