Я новичок в WPF и MVVM, и до сих пор у меня есть приложение, которое получает некоторые объекты ContactList из базы данных DB2 и отображает их информацию в пользовательском интерфейсе. В настоящее время у меня есть класс ContactListModel и класс InformationViewModel, к которому я привязываюсь. Мой класс InformationViewModel установлен как DataContext для моего просмотра. Проблема в том, что мой класс InformationViewModel также содержит мой код доступа к базе данных, т.е. соединение db и команду SQL, и я хотел бы переместить это в мой класс ContactListModel, чтобы у меня был отдельный уровень доступа к данным. Кто-нибудь может мне с этим помочь? Спасибо!
ContactListModel.cs
public class ContactListModel//: INotifyPropertyChanged
{
public int ContactListID { get; set; }
public string ContactListName { get; set; }
public ObservableCollection<AggregatedLabelModel> AggLabels { get; set; }
}
InformationViewModel.cs
public class InformationViewModel
{
public InformationViewModel()
{
GetData();
}
private ObservableCollection<ContactListModel> myContactLists;
public IEnumerable<ContactListModel> ContactLists
{
get { return myContactLists; }
}
public void GetData()
{
myContactLists = new ObservableCollection<ContactListModel>();
DB2Connection conn = null;
try
{
conn = new DB2Connection("SERVER CONNECTION;");
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message + " " + ex.InnerException);
}
//get all contactLists and their labels
DB2Command command = new DB2Command("SELECT QUERY");
command.Connection = conn;
conn.Open();
//Add unique contactLists to dictionary
Dictionary<int, ContactListModel> myContactDictionary = new Dictionary<int, ContactListModel>();
using (DB2DataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
int id = Convert.ToInt32(dr["CONTACT_LIST_ID"]);
if (!myContactDictionary.ContainsKey(id))
{
ContactListModel contactList = new ContactListModel();
contactList.ContactListID = id;
contactList.ContactListName = dr["CONTACT_LIST_NAME"].ToString();
contactList.AggLabels = new ObservableCollection<AggregatedLabelModel>()
{
new AggregatedLabelModel()
{
ID = Convert.ToInt32(dr["LABEL_ID"]),
Name = dr["LABEL_NAME"].ToString()
}
};
myContactDictionary.Add(id, contactList);
}
else
{
//populate existing contact lists with remaining labels
ContactListModel contactList = myContactDictionary[id];
contactList.AggLabels.Add
(
new AggregatedLabelModel()
{
ID = Convert.ToInt32(dr["LABEL_ID"]),
Name = dr["LABEL_NAME"].ToString()
}
);
}
}
}
conn.Close();
}