我正在使用实体框架为组织创建一个桌面应用程序,以将他们的数据输入数据库以显示他们的记录。
我创建了一个tab control
using a data template
,它已经过验证,使他们能够保存必要的必填字段,到目前为止一切都很好。
我在页面上使用了一系列不同的数据网格来显示已添加的详细信息。在此页面内,它包含一系列不同commands
的允许用户添加、更新或删除内容(取决于表,只允许他们更新)。
但这就是我陷入困境的地方。到目前为止,add 和 delete 方法工作得很好,但是当涉及到更新表时,它会抛出一个Null Reference Exception
.
以下是一些代码片段;视图模型:
public List<Employee> LoadEmployee
{
get
{
using (DBEntities context = new DBEntities())
{
var query = from e in context.Employees
select e;
return query.ToList<Employee>();
}
}
}
public void UpdateEmployee()
{
var employee = new Employee();
using (DBEntities context = new DBEntities())
{
//var emp = context.Employees.Where(e => e.EmployeeID == employee.EmployeeID).FirstOrDefault();
var emp = (from a in context.Employees
where a.EmployeeID == EmployeeID
select a).FirstOrDefault();
if (emp == null)
{
emp.EmployeeID = EmployeeID;
emp.OrganisationID = OrganisationID;
emp.Title = Title;
emp.FirstName = FirstName;
emp.Surname = Surname;
emp.Position = Position;
emp.DateOfBirth = DateOfBirth;
emp.Address = Address;
emp.Country = Country;
emp.Postcode = Postcode;
emp.PhoneNumber = PhoneNumber;
emp.MobileNumber = MobileNumber;
emp.FaxNumber = FaxNumber;
emp.Email = Email;
emp.NINumber = NINumber;
emp.ChargableResource = ChargableResource;
emp.ChargeOutRate = ChargeOutRate;
emp.TimeSheetRequired = TimeSheetRequired;
emp.WorkShift = WorkShift;
emp.WorkShift = BenefitsProvided;
//context.Employees.Attach(emp);
context.SaveChanges();
MessageBox.Show("Updated Employee Details");
}
else
{
MessageBox.Show("Unable to update selected item.");
}
}
}
public Employee _SelectedEmployee;
public Employee SelectedEmployee
{
get
{
return _SelectedEmployee;
}
set
{
if (_SelectedEmployee == value)
return;
_SelectedEmployee = value;
OnPropertyChanged("_SelectedEmployee");
}
}
代码背后:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
listview.DataContext = new EmployeeViewModel();
}
private void btnupdate_Click(object sender, RoutedEventArgs e)
{
var emp = new EmployeeViewModel();
Employee selected = listview.SelectedItem as Employee;
if (selected == null)
MessageBox.Show("You must select a 'Employee' before updating.");
else
{
UpdateEmployeeView update = new UpdateEmployeeView();
update.ShowDialog();
Window_Loaded(null, null);
}
}
xml;
IsSynchronizedWithCurrentItem="False"
ItemsSource="{Binding LoadEmployee}"
SelectedItem="{Binding SelectEmployee}" Grid.RowSpan="2">
首先,当用户从数据网格中选择一行时,我希望更新该特定行。我已将我的视图模型中的属性绑定到我的 xaml 中的文本字段,以便它传递到视图模型。我还尝试在我的视图模型中对 ID 属性进行硬编码;public int _EmployeeID = 11;
public int _OrganisationID = 4;
但这仍然会抛出Null Reference Exception
.
谁能帮我解决这个问题?我一直在尝试各种不同的方法,但仍然没有用。我是 WPF 的新手并试图实现 MVVM,显然它不是完全的 MVVM,但我正在缓慢但肯定地学习实现它的正确方法。干杯。