我要創建這個SQL查詢來LINQ:我該如何修復linq查詢來選擇組的id數?
SELECT
COUNT(m.FromUserId) AS Messages,
m.FromUserId AS UserId
FROM
dbo.ChatMessages m
INNER JOIN
dbo.ChatMessagesRead mr ON mr.ChatMessageId = m.ChatMessageId
WHERE
m.ToUserId = @toUserId
GROUP BY
m.FromUserId
我曾嘗試創建以下LINQ查詢:
var messages = from m in _dbContext.ChatMessages
join mread in _dbContext.ChatMessagesRead on m.ChatMessageId equals mread.ChatMessageId
where m.ToUserId == userId
group m by m.FromUserId into g
select new
{
UserId = g.Key,
Messages = g.Count()
};
var messagesList = messages.ToList();
但是,這是行不通的。
我該如何解決這個linq查詢?
我得到此異常:
類型中的表達 'System.Func
2[Microsoft.Data.Entity.Query.EntityQueryModelVisitor+TransparentIdentifier
2 [Project.BL.ChatMessages.ChatMessages,Project.BL.ChatMessages.ChatMessagesRead],System.Int32]' 不能使用方法'System.Collections.Generic.IEnumerable1[System.Linq.IGrouping
2的System.Func2[<>f__AnonymousType1
2 [Project.BL.ChatMessages.ChatMessages,Project.BL.ChatMessages.ChatMessagesRead],System.Int32]'參數[System.Int32, Project.BL.ChatMessages.ChatMessages]] _GroupBy [<> f__AnonymousType12,Int32,ChatMessages](System.Collections.Generic.IEnumerable
1 [<> f__AnonymousType12[Project.BL.ChatMessages.ChatMessages,Project.BL.ChatMessages.ChatMessagesRead]], System.Func
2 [<> f__AnonymousType12[Project.BL.ChatMessages.ChatMessages,Project.BL.ChatMessages.ChatMessagesRead],System.Int32], System.Func
2 [<> f__AnonymousType1`2 [Project.BL.ChatMessages.ChatMessages,Project.BL.ChatMessages.ChatMessagesRead],Project.BL.ChatMessages.ChatMessages])」'
您確定您的數據庫表中有該用戶的記錄嗎?你的代碼對我來說看起來很好。 – Shyju
@Shyju我用我得到的異常更新了我的問題。謝謝。 – Jenan
你可以請分享實體的代碼嗎?也許有一個小問題導致這個例外。 – Gabor