2017-02-22 77 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