简体   繁体   English

MVVM将数据访问与ViewModel分离

[英]MVVM separation of Data Access from ViewModel

I am new to WPF and MVVM and so far I have an app that gets some ContactList objects from the DB2 database and displays their information in the UI. 我是WPF和MVVM的新手,到目前为止,我有一个应用程序可以从DB2数据库中获取一些ContactList对象,并在UI中显示它们的信息。 Currently I have a ContactListModel class and an InformationViewModel class which I am binding to. 目前,我有一个ContactListModel类和一个要绑定的InformationViewModel类。 My InformationViewModel class is set as the DataContext for my View. 我的InformationViewModel类设置为我的视图的DataContext。 The problem is that my InformationViewModel class also contains my database access code ie db connection and SQL command and I would like to move this to my ContactListModel class so that I have a separate data access layer. 问题是我的InformationViewModel类还包含我的数据库访问代码,即db连接和SQL命令,我想将其移到ContactListModel类中,以便有一个单独的数据访问层。 Can anyone help me with this? 谁能帮我这个? Thanks! 谢谢!

ContactListModel.cs ContactListModel.cs

public class ContactListModel//: INotifyPropertyChanged
{
    public int ContactListID { get; set; }
    public string ContactListName { get; set; }
    public ObservableCollection<AggregatedLabelModel> AggLabels { get; set; }
}

InformationViewModel.cs 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();
}

You'll need to read about Repository design pattern: 您需要阅读有关存储库设计模式的信息:

That's creating a kind of in-memory-like object collection which translates your domain objects (aka "business objects", "business entities") to some format that may understand an underlying storage. 这将创建一种类似于内存的对象集合,它将您的域对象(也称为“业务对象”,“业务实体”)转换为某种可以理解底层存储的格式。

Repository will be providing the access to domain objects, meaning that your managers, models and others will understand the access to some repository as an actual collection, and that's a total abstraction letting you to separate data access logic from the business. 存储库将提供对域对象的访问权限,这意味着您的经理,模型和其他人员将把对某些存储库的访问理解为实际的集合,这是一个总的抽象,可让您将数据访问逻辑与业务分开。

Your model will have methods that are going to fill, store or look for DTO translated into domain objects and later, using your repositories, to data. 您的模型将具有将填充,存储或查找DTO的方法,这些方法将转换为域对象,然后再使用存储库转换为数据。

A rough mock up, you can add SaveContact and DeleteContact methods to the DataLayer class. 粗略地模拟一下,您可以将SaveContact和DeleteContact方法添加到DataLayer类。

    public class DataLayer
    {
        public ObservableCollection<ContactModel> GetContacts()
        {
            var tList = new ObservableCollection<ContactModel>();

            //load from db into tList

            return tList;
        }
    }

    public class ContactModel
    {
        public int ContactListID { get; set; }
        public string ContactListName { get; set; }
        public ObservableCollection<AggregatedLabelModel> AggLabels { get; set; }
    }

    public class ContactsViewModel
    {
        public ObservableCollection<ContactModel> ListOfContacts;

        public ContactsViewModel()
        {
            var dl = new DataLayer();
            ListOfContacts = dl.GetContacts();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM