c# - WPF - 将数据从 DAL 传递到 UI

标签 c# wpf mvvm

这里是新手,所以请放轻松......

我有一个正在进行的 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 传递到我的表示层?我原本的想法是在表示层上创建一个“数据”类,它从我的 DAL 调用上面的方法并返回此列表,但是,我不确定如何在没有“无法隐式地将类型列表转换为列表”的情况下执行此操作' 错误,我尝试过的是:

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

感谢您的指导。

最佳答案

根据我的阅读,您对架构的询问比任何错误更多。考虑到这一点,我想说您提供的代码实际上是某个存储库的一部分,该存储库将实现您在其他地方定义的接口(interface),并将其注入(inject)到需要该功能的任何 View 模型中。

简化的层图可以是:

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;
         }
    }
}

关于c# - WPF - 将数据从 DAL 传递到 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42402125/

相关文章:

c# - 我应该在调用 File.Delete 之前调用 File.Exists 吗?

c# - 无法在 UWP 的 Windows 运行时组件中访问我的项目中的方法和类

c# - 不显示代码中依赖属性的更改

wpf - 在 WPF 数据网格中的列之间禁用制表位

c# - 两个 C# 应用程序(32 位和 64 位)之间 IPC 的最佳方式是什么

c# - 如何在WPF中正确刷新自定义形状?

c# - 如何将所有 ListBox 的项目绑定(bind)到同一个属性?

c# - WPF 通知不适用于多个 View 模型

asp.net-mvc - 使用 ASP.NET MVC 和 MVVM 的页面初始化模式(如 knockoutjs)

c# - 密码框中的水印