[英]How can I make Sum() return 0 instead of 'null'?
我正在嘗試使用LINQ-to-entities查詢我的數據庫,其中有3個表: Room
, Conference
和Participant
。 每個房間都有很多會議,每個會議都有很多參與者。 對於每個房間,我正在嘗試統計其會議數量,以及該房間所有會議的所有參與者的總和。 這是我的查詢:
var roomsData = context.Rooms
.GroupJoin(
context.Conferences
.GroupJoin(
context.Participants,
conf => conf.Id,
part => part.ConferenceId,
(conf, parts) => new { Conference = conf, ParticipantCount = parts.Count() }
),
rm => rm.Id,
data => data.Conference.RoomId,
(rm, confData) => new {
Room = rm,
ConferenceCount = confData.Count(),
ParticipantCount = confData.Sum(cd => cd.ParticipantCount)
}
);
當我嘗試將其轉換為列表時,出現錯誤:
強制轉換為值類型'System.Int32',因為實例化值為null。 結果類型的通用參數或查詢必須使用可為空的類型。
我可以通過將“ Sum
行更改為:
ParticipantCount = confData.Count() == 0 ? 0 : confData.Sum(cd => cd.ParticipantCount)
但麻煩的是,這似乎會生成更復雜的查詢,並使查詢時間增加100毫秒。 有什么更好的辦法告訴我EF,在對ParticipantCount
求和時, confData
的空列表應該只是零,而不是拋出異常? 令人討厭的是,此錯誤僅在EF中發生; 如果我創建一個空的內存List<int>
並對其調用Sum()
,它將給我零,而不是引發異常!
使用Enumerable.DefaultIfEmpty
:
ParticipantCount = confData.DefaultIfEmpty().Sum(cd => cd.ParticipantCount)
您可以使用null合並運算符 ?? 如:
confData.Sum(cd => cd.ParticipantCount ?? 0)
我通過將Sum
行更改為:
ParticipantCount = (int?)confData.Sum(cd => cd.ParticipantCount)
令人困惑的是,即使IntelliSense告訴我正在使用Sum()
的int
重載,但在運行時它實際上是在使用int?
重載,因為confData
列表可能為空。 如果我明確告訴它返回類型是int?
它返回null
的空列表項,以后我可以空聚結null
秒至零。
無需嘗試讓EF生成返回0而不是null的SQL查詢,而是在像這樣處理客戶端的查詢結果時進行更改:
var results = from r in roomsData.AsEnumerable()
select new
{
r.Room,
r.ConferenceCount,
ParticipantCount = r.ParticipantCount ?? 0
};
AsEnumerable()
強制對SQL查詢進行求值,隨后的查詢運算符是客戶端LINQ-to-Objects。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.