【发布时间】:2010-05-11 18:26:54
【问题描述】:
我使用这一面来创建我的演示应用程序 http://windowsclient.net/learn/video.aspx?v=314683
该站点对我的入门非常有用,在他们的示例中,他们创建了一个名为 EmployeeRepository.cs 的文件,该文件似乎是数据的来源。在他们的示例中,数据是硬连接在代码中的。所以我正在尝试学习如何从数据源(如数据库)获取数据。在我的具体情况下,我想从 Microsoft Access 数据库中获取数据。 (只读,所以我只会使用 SELECT 命令)。
using System.Collections.Generic;
using Telephone_Directory_2010.Model;
namespace Telephone_Directory_2010.DataAccess
{
public class EmployeeRepository
{
readonly List<Employee> _employees;
public EmployeeRepository()
{
if (_employees == null)
{
_employees = new List<Employee>();
}
_employees.Add(Employee.CreateEmployee("Student One", "IT201", "Information Technology", "IT4207", "Building1", "Room650"));
_employees.Add(Employee.CreateEmployee("Student Two", "IT201", "Information Technology", "IT4207", "Building1", "Room650"));
_employees.Add(Employee.CreateEmployee("Student Three", "IT201", "Information Technology", "IT4207", "Building1", "Room650"));
}
public List<Employee> GetEmployees()
{
return new List<Employee>(_employees);
}
}
}
我发现了另一个使用 Access DB 但不符合 MVVM 的示例。所以我试图弄清楚如何将数据库文件添加到项目中,如何连接它并将其绑定到列表框(我还没有那么远)。以下是我修改后的文件
using System.Collections.Generic;
using Telephone_Directory_2010.Model;
// integrating new code with working code
using Telephone_Directory_2010.telephone2010DataSetTableAdapters;
using System.Windows.Data;
namespace Telephone_Directory_2010.DataAccess
{
public class EmployeeRepository
{
readonly List<Employee> _employees;
// start
// integrating new code with working code
private telephone2010DataSet.telephone2010DataTable employeeTable;
private CollectionView dataView;
internal CollectionView DataView
{
get
{
if (dataView == null)
{
dataView = (CollectionView) CollectionViewSource.GetDefaultView(this.DataContext);
}
return dataView;
}
}
public EmployeeRepository()
{
if (_employees == null)
{
_employees = new List<Employee>();
}
telephone2010TableAdapter employeeTableAdapter = new telephone2010TableAdapter();
employeeTable = employeeTableAdapter.GetData();
this.DataContext = employeeTable;
}
public List<Employee> GetEmployees()
{
return new List<Employee>(_employees);
}
}
}
我在构建时收到以下错误消息
错误 1 'Telephone_Directory_2010.DataAccess.EmployeeRepository' 不包含 'DataContext' 的定义并且没有扩展方法 'DataContext' 接受类型为 'Telephone_Directory_2010.DataAccess.EmployeeRepository' 的第一个参数(您是否缺少使用指令还是程序集参考?)C:\Projects\VS2010\Telephone Directory 2010\Telephone Directory 2010\DataAccess\EmployeeRepository.cs 23 90 Telephone Directory 2010
【问题讨论】:
-
在我看来,您的问题与 MVVM 并不特别相关,而更多的是如何在 C# 中将数据访问层写入 Access 的问题?
-
马蒂亚斯,你可能是对的。我对.Net 比较陌生。当 .Net 仍处于 1.0 阶段时,我做了一些 WinForms,然后我就不必使用它了。所以我熟悉 C# 和它的语法,但我完全不知道如何将我的数据从 Access DB 获取到我的 DataGrid(或 ListBox)。这是一个班级,我想真正学习如何正确地做它(而不是草率的代码来让它工作)
-
从 C# 对 Jet/ACE 数据的数据访问不需要重新编写。但这个问题确实与 Access 无关。
标签: c# ms-access mvvm data-access-layer