Asp.net-Mvc
LINQ to Entities 無法辨識方法異常
我有這樣的事情
SecuritySearcher sc = new SecuritySearcher(); Dictionary<string, bool> groupsMap = sc.GetUserGroupMappings(domainName, currentUser, distGroups.ToList()); IQueryable<HotelTravel> groupq = (from hotel in qHs join hp in qHps on hotel.HotelTravelId equals hp.HotelTravelId where !string.IsNullOrEmpty(hp.GroupName) && groupsMap.ContainsKey(hp.GroupName) && groupsMap[hp.GroupName] == true select hotel);在執行 Linq 語句時,它會拋出異常,說 LINQ to Entities 無法辨識“Boolean ContainsKey(System.String)”方法,並且該方法無法轉換為儲存表達式。
為了將您的表達式轉換為數據庫查詢,數據庫必須以某種方式知道您的字典的內容,並有辦法從查詢中訪問它。SQL 中沒有字典機制,但這沒關係,因為您不需要字典,因為您只是在查找值為某個常量的鍵。您可以將該組鍵轉換為列表,並查看該列表是否包含您要查找的內容:
var groupsList = (from kvp in groupsMap // find all keys in groupsMap where kvp.Value == true // where the value is set to True select kvp.Key).ToList(); IQueryable<HotelTravel> groupq = from hotel in qHs join hp in qHps on hotel.HotelTravelId equals hp.HotelTravelId where !string.IsNullOrEmpty(hp.GroupName) && groupsList.Contains(hp.GroupName) select hotel;不過,我懷疑您實際上並沒有將空字元串作為字典中的鍵,這意味著您可以擺脫
IsNullOrEmpty呼叫而只使用where groupsList.Contains(hp.GroupName).