【问题标题】:How to retrieve the Value of KeyValuePair from database in C#?如何在 C# 中从数据库中检索 KeyValuePair 的值?
【发布时间】:2020-01-06 05:19:51
【问题描述】:

我正在从事一个涉及 KeyValuePair 的项目。我有 int 作为键,字符串作为值。

我想要的是从 KeyValuePair 中获取值。

我有这个代码:

var list = new List<KeyValuePair<int, string>>()
{
  new KeyValuePair<int, string>(obj,_Obj.Questions)
            };

Dictionary<int, string> d = new Dictionary<int, string>
{
      { 1, "Welcome, How are you?" },
      { 2, "Tell me something about yourself."},
      { 3, "How much experience do you have?"},
};

因此,如果您在 KVP 中看到字符串 Values,例如“Welcome, How are you?”、“Tell me something about your”等,则是静态的。所有这些值都已经存在于我的本地数据库中。我只想要数据库中的这些字符串值。

我正在使用 MS SQL 数据库

这可能吗??

【问题讨论】:

  • d[1] 将为您提供 1 的 KVP 价值
  • 不完全确定我是否理解,因为您提到了数据库。但是,如果您想要键值对中的值,您将使用 .Value。 docs.microsoft.com/en-us/dotnet/api/…。如果您尝试从字典中获取每个值,则可以循环字典并访问每个项目的 .Value。
  • KeyValuePair 是如何存储在 Db 中的?你能分享一下你的桌子是什么样子的吗?

标签: c# sql-server dictionary keyvaluepair


【解决方案1】:

您可以使用任何 ORM,例如 Entity Framework,但是,我将提供一个手动操作的示例:

var list = new List<KeyValuePair<int, string>>()

using(var connection = new SqlConnection(connectionString)) 
using(var command = new SqlCommand("SELECT * FROM interview_Table", connection))
using(var reader = command.ExecuteReader())
{
    if (connection.State != ConnectionState.Open) { connection.Open(); }

    if (reader.HasRows)
    {
        foreach (var row in reader)
        {
            //ensurance
            var isValidId = int.TryParse(row["Id"]?.ToString(), int out id);

            var description = row["Description"]?.ToString();       

            // only fetch rows with a valid id number with description that is not empty or null
            if(isValidId && !string.IsNullOrEmpty(description))
            {
                list.Add(new KeyValuePair<int, string>(id, description));
            }                   
        }
    }
}

【讨论】:

  • 我在 foreach 循环中使用了 DataRow 而不是 var row。但它给了我错误说“无法将'System.Data.Common.DataRecordInternal'类型的对象转换为'System.Data.DataRow'”
  • @RohanRao reader 返回DbDataRecord,与DataRow 没有继承关系。因此,开箱即用不可能将其转换为DataRow!。这就是当您将 var 更改为 DataRow 时收到该错误的原因。要解决它,您需要找到解决方法,例如通过 DataTable 加载阅读器,然后将其转换为 DataRow(例如 DataTable.Load(reader))。
【解决方案2】:

是的,你的要求是可能的。

您必须建立数据库连接并运行查询以提取所需的数据。收到数据后,将其放入集合中。

此集合可以包含 KeyValuePair,就像您编写的那样您可以创建一个复制表结构的类并拥有这些对象的集合。

您还可以更进一步,研究诸如实体框架之类的东西。

祝你好运!

【讨论】:

    【解决方案3】:

    您可以使用 EntityFramework ToDictionary 函数进行此映射。

    var test = await this.dbcontext.InterviewQuestions
        .Select(x => new { x.Id, x.Description})
        .AsEnumerable()
        .ToDictionaryAsync(xkvp  => xkvp.Id, xkvp.Description);
    
    1. 如果你使用的是.net core,可以查看getting started with EF core
    2. 如果您使用.net,可以查看getting started with EF 6

    我个人最喜欢的一个code first with EF 6 from existing DB 将生成您需要的大部分代码。

    【讨论】:

    • 谢谢 :) 我收到一个错误 - 第二个参数应该是 cancelToken 而不是 x.Description。
    • 尝试更新版本。 ToDictionaryAsync 只会将InterviewQuestion 对象映射到键值,因此您只能为异步部分提供键和取消令牌。
    猜你喜欢
    • 2014-10-07
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多