首页 > 解决方案 > 如何在 C# 中将数据库值存储在字典中

问题描述

当我收到一个国家名称时,我想在我的数据库中搜索一个国家名称列表并获取与国家名称相关的 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;
    }

但是,如您所见,每次我想获取国家名称列表时都必须查询数据库。我想拥有它,以便将此列表存储在字典中,而我可以访问字典。

有谁知道我可以如何改进我的代码,这样我就不必每次都访问数据库?

标签: c#sqldatabase

解决方案


让我们为此做一个延迟加载!

private Dictionary<string, Country> _countryNames = null;

public Dictionary<string, Country> CountryNames
{
    get
    {
         if(_countryNames == null)
         {
             _countryNames = new Dictionary<int, Country>();
             foreach(var country in GetCountries())
             {
                 _countryNames.Add(country.Name, country)
             }
         }
         return _countryNames;
    }
}

public static int GetCountryId(string countryName)
{
    Country result;
    CountryNames.TryGetValue(countryName, out result);
    if (result == null) return 0;
    return result.Id;
}

private static IEnumerable<Country> GetCountries()
{
    string query = "SELECT Id, Name FROM Countries";
    return Common.GetCollection<Country>(Properties.Settings.Default.DbConnectionString, query);
}

但通常让数据库做这件事会更好:根据需要在那里运行查询,将过滤器字符串传递给数据库。不幸的是,The 对Common.GetCollection<T>()我们隐藏了这种能力。该query变量应如下所示:

string query = "SELECT Id, Name FROM Countries WHERE Name = @CountryName";

但是从这里的问题中不清楚如何提供@CountryName参数值。您不应该的是使用字符串替换或插值将值直接包含在查询字符串中。那将是非常糟糕的;它创建了一种严重的安全形式,称为 SQL 注入。


推荐阅读