I am new to WPF and MVVM, and so far I have an application that retrieves some ContactList objects from the DB2 database and displays their information in the user interface. Currently, I have a ContactListModel class and an InformationViewModel class that I am contacting. My InformationViewModel class is set as a DataContext for my view. The problem is that my InformationViewModel class also contains the ie db connection database access code and SQL command, and I would like to move this to my ContactListModel class so that I have a separate data access level. Can anyone help me with this? Thank!
ContactListModel.cs
public class ContactListModel
{
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);
}
DB2Command command = new DB2Command("SELECT QUERY");
command.Connection = conn;
conn.Open();
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
{
ContactListModel contactList = myContactDictionary[id];
contactList.AggLabels.Add
(
new AggregatedLabelModel()
{
ID = Convert.ToInt32(dr["LABEL_ID"]),
Name = dr["LABEL_NAME"].ToString()
}
);
}
}
}
conn.Close();
}
source
share