c# - 如何在 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;
}
但是,如您所见,每次我想获取国家名称列表时都必须查询数据库。我想拥有它,以便将此列表存储在字典中,而我可以访问字典。
有谁知道我可以如何改进我的代码,这样我就不必每次都访问数据库?
解决方案
让我们为此做一个延迟加载!
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 注入。
推荐阅读
- php - 使用 php soap 使用 OpenTravel WSDL
- android - 注册和注销广播接收器?
- apache-camel - 动态更改属性占位符的值
- ontology - owl api state ObjectProperty 个人之间的关系来自进口
- html - 从 html 表单向 jsp 提交“null”
- node.js - |节点.JS| 每当我得到 params.id 时,我就会得到 jumbotron.css
- java - 在 Eclipse 中对 Java 9 模块化项目进行 JUnit 测试
- ldap - CAS 5.2.4 cas.properties 位置
- c# - 为什么 C# 在 XDocument 中留下未闭合的标签?
- pycharm - graphlab.SFrame.show() 错误:请求的端口不可用:无