我是 WPF 和 MVVM 的新手,到目前为止我有一个应用程序可以从 DB2 数据库获取一些 ContactList 对象并在 UI 中显示它们的信息。目前我有一个 ContactListModel 类和一个要绑定(bind)的 InformationViewModel 类。我的 InformationViewModel 类被设置为我的 View 的 DataContext。问题是我的 InformationViewModel 类还包含我的数据库访问代码,即数据库连接和 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();
}
最佳答案
您需要阅读存储库设计模式:
这就是创建一种类似于内存中的对象集合,将您的领域对象(也称为“业务对象”、“业务实体”)转换为某种可以理解底层存储的格式。
存储库将提供对域对象的访问,这意味着您的经理、模型和其他人将把对某些存储库的访问理解为实际集合,这是一个完全抽象,让您可以将数据访问逻辑与业务分开。
您的模型将具有用于填充、存储或查找 DTO 的方法,这些 DTO 已转换为域对象,随后使用您的存储库转换为数据。
关于c# - 数据访问与 ViewModel 的 MVVM 分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4862709/