我開發一個ASP.NET MVC的網站,並正在尋找一種方法來改善這個程序。可以在LINQ級別或SQL Server級別上進行改進。我希望我們可以在一個查詢調用中做到這一點。此查詢是否可以改進查找丟失的密鑰? (SQL或LINQ)
我們沒有限制,每Key
必須有每個LanguageId
價值,堪與業務邏輯不允許這樣contraint。但是,在應用程序級別,我們要警告管理員,某個鍵缺少某些語言值。所以,我有這個類和查詢:
public class LocalizationKeyWithMissingCodes
{
public string Key { get; set; }
public IEnumerable<string> MissingCodes { get; set; }
}
這種方法得到的密鑰列表,以及任何遺漏代碼(例如,如果我們有EN +日本+ CH語言代碼,關鍵只值EN + CH,該列表將包含JP):
public IEnumerable<LocalizationKeyWithMissingCodes> GetAllKeysWithMissingCodes()
{
var languageList = Utils.ResolveDependency<ILanguageRepository>().GetActive();
var languageIdList = languageList.Select(q => q.Id);
var languageIdDictionary = languageList.ToDictionary(q => q.Id);
var keyList = this.GetActive()
.Select(q => q.Key)
.Distinct();
var result = new List<LocalizationKeyWithMissingCodes>();
foreach (var key in keyList)
{
// Get missing codes
var existingCodes = this.Get(q => q.Active && q.Key == key)
.Select(q => q.LanguageId);
// ToList to make sure it is processed at application
var missingLangId = languageList.Where(q => !existingCodes.Contains(q.Id))
.ToList();
result.Add(new LocalizationKeyWithMissingCodes()
{
Key = key,
MissingCodes = missingLangId
.Select(q => languageIdDictionary[q.Id].Code),
});
}
result = result.OrderByDescending(q => q.MissingCodes.Count() > 0)
.ThenBy(q => q.Key)
.ToList();
return result;
}
我覺得我目前的解決辦法是不好的,因爲它使查詢調用每個鍵。有沒有辦法通過使其更快或者在一個查詢調用中打包來改進它?
編輯:這是答案的最終查詢:
public IQueryable<LocalizationKeyWithMissingCodes> GetAllKeysWithMissingCodes()
{
var languageList = Utils.ResolveDependency<ILanguageRepository>().GetActive();
var localizationList = this.GetActive();
return localizationList
.GroupBy(q => q.Key, (key, items) => new LocalizationKeyWithMissingCodes()
{
Key = key,
MissingCodes = languageList
.GroupJoin(
items,
lang => lang.Id,
loc => loc.LanguageId,
(lang, loc) => loc.Any() ? null : lang)
.Where(q => q != null)
.Select(q => q.Code)
}).OrderByDescending(q => q.MissingCodes.Count() > 0) // Show the missing keys on the top
.ThenBy(q => q.Key);
}
這太神奇了!我永遠無法想到它。 –
參加實踐:) – devuxer