如何从实体框架中的可空关系中选择非空值 [英] How to select non nullables from nullable relation in Entity Framework
问题描述
我正在做一个基于实体框架和Scott Guthrie的动态Linq库的报告工具。
I am making a reporting tool that is based off Entity Framework and Scott Guthrie's Dynamic Linq library.
当尝试选择不可为空时,我遇到了一个错误当相关的记录不总是在相关表中的字段。例如,我有一个参与者表具有一个可空的外键到一个团队表。这是因为一些参与者将会在一个团队中,有些参与者将不会。这个障碍是,我想拉一个报告,显示参与者名单以及他们的团队信息,如果他们在一个团队。团队表中的其中一列不可空,因此当我尝试使用标准投影或动态列表选择它时:
I have run into a snag when trying to select a non nullable field from a related table when the related record isnt always there. For example, I have a Participant table that has a nullable foreign key to a Team table. This is because some participants will be on a team and some wont. The snag is that I want to pull a report that shows a list of participants along with some of their team information IF they are on a team. One of the columns on the team table isn't nullable so when I try to select it using either a standard projection or a dynamic one:
var standardProjection = data.Select(i => new
{
i.FirstName,
i.ParticipantTeam.CaptainPickupFlg <--- Non Nullable Boolean
});
var dynamicProjection = data.Select("new (FirstName, ParticipantTeam.CaptainPickupFlg)");
尝试枚举结果时收到错误:
I get an error when trying to enumerate the results:
转换为值类型Boolean失败,因为实例化值为null。结果类型的泛型参数或查询必须使用可空类型。
"The cast to value type 'Boolean' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."
如何避免这个错误,只有参与者Team.CaptainPickupFlg在匿名类型中被实例化为可空的布尔?
How can I avoid this error and just have the ParticipantTeam.CaptainPickupFlg just materialized as a nullable bool in the anonymous type?
ScottGu的动态临床: http ://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
ScottGu's Dynamic Linq: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
推荐答案
data.Where( i => i.ParticipantTeam != null ).Select( i=> new
{
i.FirstName,
i.ParticipantTeam.CaptainPickupFlg
});
如果您需要所有参与者,您有两个选择:
If you need all the participants, you have two options:
-
如果您可以负担返回匿名类型的可空字段:
If you can afford the nullable field in returned anonymous type:
var standardProjection = data.Select(i => new
{
i.FirstName,
CaptainPickupFlg = (bool?)i.ParticipantTeam.CaptainPickupFlg
});
如果这不是您的选择,您应该决定该字段的默认值:
If that's not an option for you, you should decide on the default value for that field:
var standardProjection = data.Select(i => new
{
i.FirstName,
CaptainPickupFlg = ((bool?)i.ParticipantTeam.CaptainPickupFlg) ?? false
});
其默认值为 false
。
这篇关于如何从实体框架中的可空关系中选择非空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!