C# 如何将数据库值添加到包含类作为对象的字典中
我有一个字典,其中包含一个字符串作为TKey,一个类“Component”作为TValue。 我的问题是,a希望将数据库值和xml值添加到类字段中 这是我的类组件:C# 如何将数据库值添加到包含类作为对象的字典中,c#,sql-server,xml,linq,C#,Sql Server,Xml,Linq,我有一个字典,其中包含一个字符串作为TKey,一个类“Component”作为TValue。 我的问题是,a希望将数据库值和xml值添加到类字段中 这是我的类组件: public class Component { public string ComponentNr { get; set; } public string Omschrijving { get; set; } public int Aantal { get; set; }
public class Component
{
public string ComponentNr { get; set; }
public string Omschrijving { get; set; }
public int Aantal { get; set; }
public int Pos { get; set; }
}
我已经用xml属性值填充了ComponentNr和Pos字段,现在我想从数据库中获取“Aantal”和“Omschrijving”,其中数据库值“artcode”是ComponentNr
查询:
SqlCommand dgCommand = new SqlCommand("select g.artcode, i.Description, sum(g.aantal*-1) as aantal " +
"from gbkmut g " +
"join Items i on g.artcode = i.ItemCode " +
"where 1=1 and g.project=@projectnr and g.reknr=3000 and g.bud_vers='MRP' and g.operation='VOORSMD' and g.artcode !='H MAN' and i.Description not like 'pcb %' " +
"group by g.artcode, i.Description, g.aantal ", conn);
这就是我目前用xml属性值填充字典的方法:
Dictionary<string, Component> resultaten = componenten;
List<string> files = fileList;
string file;
file = files.Find(x => x.Contains(faberNr));
XDocument xdoc = XDocument.Load(file);
List<Component> components = xdoc.Descendants("Part").Select(x => new Component()
{
ComponentNr = (string)x.Elements().Where(y => y.Attribute("PartsName") != null)
.Select(y => (string)y.Attribute("PartsName")).FirstOrDefault(),
Pos = (int)x.Descendants().Where(y => y.Attribute("Setno") != null)
.Select(y => (int)y.Attribute("Setno")).FirstOrDefault()
}).ToList();
resultaten = components.GroupBy(x => x.ComponentNr, y => y).ToDictionary(x => x.Key, y => y.FirstOrDefault());
return resultaten;
我的实际产出是:
Key = 38292000
Value = Component
Aantal = 16
ComponentNr = 38292000
Omschrijving = Omschrijving123
Pos = 12
Key = 38292000
Value = Component
Aantal = 0
ComponentNr = 38292000
Omschrijving = null
Pos = 12
因此,步骤1是从xml填充
字典。然后,第2步是运行数据库查询,以完成填写存储在字典中的组件对象
ComponentNr
是字典
的键,在“artcode”
字段中的数据库查询中有ComponentNr
,因此您只需使用“artcode”
从字典
中查找值,然后对其进行修改
//reader是从SqlCommand获得的SqlDataReader的实例。
//resultaten是您先前填充的字典。
//如果这些列在数据库中可以为null,请不要忘记检查它们的DBNull.Value。
string componentNr=Convert.ToString(读卡器[“artcode”]);
if(resultaten.TryGetValue(componentNr,out Component value))
{
value.Aantal=Convert.ToInt32(读卡器[“Aantal”]);
value.Omschrijving=Convert.ToString(读卡器[“说明]);
}
其他的
{
//组件存在于数据库中,但不在字典中。
}
为什么需要“
”?@jdweng这是一个输入错误,它们来自databaseComponent=resultaten[“38292000”];成分A=16;