[英]Linq Left Outer Join - DefaultIfEmpty Error
There is a collection of devices types, some of which support configuration setting(s). 有一组设备类型,其中一些支持配置设置。 I'm trying to get a list of all device types, and any applicable settings.
我正在尝试获取所有设备类型和任何适用设置的列表。
This query isn't picking up devices that have no DeviceParameters. 此查询未获取没有DeviceParameters的设备。 If I add the .DefaultIfEmpty() as shown below, I get this error:
如果我添加.DefaultIfEmpty(),如下所示,我收到此错误:
"The cast to value type 'Int64' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type." “转换为值类型'Int64'失败,因为具体化值为null。结果类型的泛型参数或查询必须使用可空类型。”
What's the correct synatx for DefaultIfEmpty? 什么是DefaultIfEmpty的正确synatx?
var Devices = from d in dc.DeviceTypes
join p in dc.DeviceParameters on d.TypeID equals p.TypeID into tmpTable
from items in tmpTable.DefaultIfEmpty()
group items by d.DeviceName into g
select new
{
DeviceName = g.Key,
settings = from s in g
select new
{
ParamName = s.ParamName,
Param1 = s.Param1,
Param2 = s.Param2,
Param3 = s.Param3
}
};
If you have defined the foreign key relationship, I think the solution is pretty straightforward, unless I'm missing something: 如果你已经定义了外键关系,我认为解决方案非常简单,除非我遗漏了一些东西:
var Devices = dc.DeviceTypes
.Select(p=>new
{
DeviceName = p.DeviceName ,
settings = p.DeviceParameters
.Select(q=>new
{
ParamName = p.ParamName,
Param1 = q.Param1,
Param2 = q.Param2,
Param3 = q.Param3
})
});
Anyways, I would probably do the settings part this way: 无论如何,我可能会这样设置部分:
settings = p.DeviceParameters.ToList()
I believe the issue that you are seeing with your query is that by using the DefaultIfEmpty()
call you are then trying to pull values out of a null object. 我相信您在查询中看到的问题是,通过使用
DefaultIfEmpty()
调用,您将尝试从null对象中提取值。 If you have a valid DeviceType but don't have any DeviceParameters mapped then when it is trying to materialize the settings property with this statement: 如果您有一个有效的DeviceType但没有映射任何DeviceParameters,那么当它尝试使用以下语句实现settings属性时:
settings = from s in g
select new
{
ParamName = s.ParamName,
Param1 = s.Param1,
Param2 = s.Param2,
Param3 = s.Param3
}
It is trying to create a new object and the object for "s" is null so trying to access the property ParamName or Param1, etc. won't work. 它正在尝试创建一个新对象,并且“s”的对象为null,因此尝试访问属性ParamName或Param1等将无法正常工作。 I tried the same code within LINQPad and when I removed the DefaultIfEmpty() call then everything worked.
我在LINQPad中尝试了相同的代码,当我删除DefaultIfEmpty()调用时,一切正常。
Without knowing the properties and their types I can't be certain but like I said, based on implementing similar code in LINQPad I got similar results. 在不知道属性及其类型的情况下,我无法确定,但就像我说的,基于在LINQPad中实现类似的代码,我得到了类似的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.