Как добавить значения базы данных в словарь, содержащий класс в качестве объекта - PullRequest
0 голосов
/ 11 октября 2019

У меня есть словарь, содержащий строку как TKey, и класс "Component" как TValue. Моя проблема в том, что я хочу добавить значения базы данных и значения xml в поля класса.

Это мой компонент класса:

public class Component
    {
        public string ComponentNr { get; set; }
        public string Omschrijving { get; set; }
        public int Aantal { get; set; }
        public int Pos { get; set; }
    }

Я уже заполнил поля ComponentNr и Pos xmlзначения атрибутов и теперь я хочу получить "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 Ответ

1 голос
/ 11 октября 2019

Итак, шаг 1 состоит в заполнении Dictionary<string, Component> из xml. Затем шаг 2 - запустить запрос к базе данных, чтобы завершить заполнение Component объектов, которые хранятся в Dictionary?

ComponentNr - ключ в Dictionary, и у вас есть ComponentNr из вашего запроса к базе данных в поле "artcode", так что вы просто посмотрите значение из Dictionary, используя "artcode", а затем измените его.

// reader is an instance of SqlDataReader you got from the SqlCommand.
// resultaten is the Dictionary<string, Component> that you populated earlier.
// If these columns can be null in the database, don't forget to check them for DBNull.Value.
string componentNr = Convert.ToString(reader["artcode"]);
if (resultaten.TryGetValue(componentNr, out Component value))
{
   value.Aantal = Convert.ToInt32(reader["aantal"]);
   value.Omschrijving = Convert.ToString(reader["Description"]);
}
else
{
   // Component exists in the database but not in the Dictionary.
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...