我有一長串手工制作的物品串列,其中包含一個試劑字典,其中一個 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();
}
當我用谷歌搜索它時,我得到了很多關于如何使用字典的點擊,但沒有關于如何存盤一個有字典作為成員的類。誰能指出我正確的方向?
uj5u.com熱心網友回復:
我根本無法與 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 資料型別,但我不會打擾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/510178.html
