2017-02-22 76 views
2

福利局在这里,所以请去容易....WPF - 从DAL将数据传递到UI

我在旅途中的WPF项目,我创建了一个数据访问层,我得到我所需要的数据与下面的代码:

public static List<Model.CountryList> GetAllCountriesList() 
    { 

     SqlConnection connection = new DatabaseConnection().ConnectToBooze(); 
     SqlCommand cmd = new SqlCommand(); 
     SqlDataReader reader; 
     SqlDataAdapter da = new SqlDataAdapter(); 

     cmd.CommandText = "dbo.spGetAllCountries"; 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Connection = connection; 

     connection.Open(); 

     reader = cmd.ExecuteReader(); 

     var CompanyList = new List<Model.CountryList>(); 

     while (reader.Read()) 
     { 
      while (reader.Read()) 
      { 
       var Cli = new Model.CountryList(); 
       Cli.CountryID = Convert.ToInt32(reader["CountryID"]); 
       Cli.CountryName = reader["CountryName"].ToString(); 
       //Add the country to Country List 
       CompanyList.Add(Cli); 
      } 
     } 
     //Return list 
     return CompanyList; 
    } 

我在挣扎的是,我如何将这从DAL传递到我的表示层?我曾经想过的是在表现层上创建一个'Data'类,它从我的DAL调用上面的方法并返回这个列表,但是,我不确定如何做到这一点,而不会'不能隐式地将类型列表转换为列表'错误,我曾试过的是:

public static List<Model.CountryList> GetAllCountries() 
    {  
     return DataAccessLayer.DatabaseGets.GetAllCountriesList(); 
    } 

感谢您的指导。

+0

似乎没给我。你可以更具体一些你看到的错误。也许发布整个错误? – Versatile

+0

好吧,我是个白痴。我在表示层使用了不同的模型,因此出现了错误。现在通过在DAL中完全引用模型来解决它。谢谢你的帮助。 – Leonidas199x

+0

在发布答案后马上看到你的评论,很高兴你明白了! – JSteward

回答

0

MVVM只是一种分离问题和恕我直言,一个荣耀的三层数据系统的方式。

如何将此从DAL传递到我的表示层?

地点/读出的数据到MVVM的​​和从视图这将在与它的绑定控件上的任何负载的视图经由INotifyPropertyChange从VM通知(所有在后台)消耗它。

见我的MVVM博客文章中,让你开始:Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding

3

通过我看了你的要求更多的架构比任何错误。考虑到这一点,我认为你提供的代码实际上是某个存储库的一部分,该存储库将实现一个你定义的接口,并将其注入到任何需要该功能的视图模型中。

简化层状图可能是:不管你的代码所提供

UI -> ViewModel -> Model <- DAL 

namespace MyApp.Model 
{ 
    public interface IMyRepo 
    { 
     IEnumerable<Model.CountryList> GetAllCountries(); 
    } 
} 

namespace MyApp.DAL 
{ 
    public class MyRepo : IMyRepo 
    { 
     IEnumerable<Model.CountryList> GetAllCountries() 
     { 
      /** 
      data access 
      **/ 
     } 
    } 
} 

namespace MyApp.ViewModel 
{ 
    public class MainViewModel : ViewModelBase 
    { 
     public MainViewModel(IMyRepo repo) 
     { 
       this.Repo = repo; 
     } 
    } 
} 
+0

这很好,谢谢你 – Leonidas199x