【发布时间】:2019-01-10 10:12:43
【问题描述】:
我是 WPF 和 MVVM 的新手,到目前为止,我有一个应用程序可以从 DB2 数据库中获取一些 ContactList 对象并在 UI 中显示它们的信息。目前我有一个 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();
}
【问题讨论】: