繁体   English   中英

C# 在 SQL 数据库中存储具有字典作为字段的 object

[英]C# Store an object that has a dictionary as a field in SQL Database

我有一长串手工制作的物品,其中包含一个试剂字典,其中一个 int 是试剂的 id,一个 int 是要使用的数量。

我不知道如何将此列表存储在表格中。

public class CraftedItem : IEquatable<CraftedItem>
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public Dictionary<int, int> ReagentsAndQuantities { get; set; }
    public int RecipeId { get; set; }

    public bool Equals(CraftedItem other)
    {
        if (other is null)
            return false;

        return Id == other.Id;
    }

    public override bool Equals(object obj) => Equals(obj as Recipe);
    public override int GetHashCode() => Id.GetHashCode();
}

当我用谷歌搜索它时,我得到了很多关于如何使用字典的信息,但没有关于如何存储一个有字典作为成员的 class 的信息。 谁能指出我正确的方向?

我根本无法与 EF 交谈,但如果您只是使用普通的 ADO 连接,您的字典只需要一个单独的表:

create table crafted_item (
  id int primary key not null,
  name text,
  recipe_id int
);

create table reagents_and_quantities (
  crafted_item_id int not null,
  reagent int not null,
  quantity int,
  constraint reagents_and_quantities_pk primary key (crafted_item_id, reagent)
);

诀窍就是您用来填充数据的 CRUD。 我会认为像这样简单的事情会起作用。 假设您的 CRUD GetAll 方法如下所示:

  List<CraftedItem> results = new List<CraftedItem>();

  using (NpgsqlCommand cmd = new NpgsqlCommand("select * from crafted_item", conn))
  {
      using (NpgSqlDataReader reader = cmd.ExecuteReader())
      {
          while (reader.Read())
          {
              CraftedItem foo = new CraftedItem();
              // populate the properties
              foo.ReagentsAndQuantities = new Dictionary<int, int>();
              results.Add(foo);
          }
          reader.Close();
      }
  }

然后,在关闭连接之前,再执行一次并动态绑定字典条目:

  using (NpgsqlCommand cmd = new NpgsqlCommand("select * from reagents_and_quantities", conn))
  {
      using (NpgSqlDataReader reader = cmd.ExecuteReader())
      {
          while (reader.Read())
          {
              int craftedItem = reader.GetInt32(0);
            
              CraftedItem foo = results.Find(x => x.Id == craftedItem);
              if (foo != null)
              {
                  int reagent = reader.GetInt32(1);
                  int qty = reader.GetInt32(2);
                  foo.ReagentsAndQuantities[reagent] = qty;
              }
          }
          reader.Close();
      }
  }

我有点懒,但希望你能明白。 大概您的“GetAll”将具有某种形式的 where 子句,因此您当然希望将其应用于 reagents_and_quantities 详细信息以简化。

或者,您可以使用 JSON 数据类型,但我不会打扰。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM