【发布时间】:2019-04-01 21:54:10
【问题描述】:
当我收到一个国家名称时,我想在我的数据库中搜索一个国家名称列表并获取与国家名称相关联的 id。目前我有;
public static int GetCountryId(string countryName)
{
int countryId = 0;
if (!string.IsNullOrEmpty(countryName))
{
var listOfCountries = GetCountries();
var match = listOfCountries.FirstOrDefault(item => (item.Name).Contains(countryName));
if (match != null)
{
countryId = match.Id;
}
}
return countryId;
}
private static List<Country> GetCountries()
{
string query = $"SELECT Id, Name FROM Countries";
List<Country> cases = Common.GetCollection<Country>(Properties.Settings.Default.DbConnectionString, query);
return cases;
}
但是,如您所见,每次我想获取国家名称列表时都必须查询数据库。我想拥有它,以便将此列表存储在字典中,而我可以访问字典。
有谁知道我可以如何改进我的代码,这样我就不必每次都访问数据库了?
【问题讨论】: