WPF + EF.上下文.SaveChanges() 不起作用
本文关键字:不起作用 SaveChanges 上下文 EF WPF | 更新日期: 2023-09-27 18:30:41
我是一个新的WPF开发人员,我正在为一家旅馆编写一个WPF项目。我使用实体框架和数据库优先方法。在UI中,我有一个绑定到学生集合的数据网格。并且宣布了"RowEditEnding"
和"AddingNewItem"
事件。
所以我想要的只是能够编辑和添加新学生。一切正常,没有错误SaveChanges()
但该方法不会将实体保存到数据库中。
我的MainWindow.xaml.cs
代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
HostelDBEntities db = new HostelDBEntities();
private bool isInsertMode = false;
private bool isBeingEdited = false;
private ObservableCollection<Student> GetStudentsList()
{
var list = from e in db.Students select e;
return new ObservableCollection<Student>(list);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
studentsGrid.ItemsSource = GetStudentsList();
}
private void studentsGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
Student student = new Student();
Student st = e.Row.DataContext as Student;
if (isInsertMode)
{
var InsertRecord = MessageBox.Show("Do you want to add a new student?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (InsertRecord == MessageBoxResult.Yes)
{
student.FirstName = st.FirstName;
student.LastName = st.LastName;
student.Patronymic = st.Patronymic;
db.Students.Add(student);
db.SaveChanges();
}
else studentsGrid.ItemsSource = GetStudentsList();
}
db.SaveChanges();
}
private void studentsGrid_AddingNewItem(object sender, AddingNewItemEventArgs e)
{
isInsertMode = true;
}
}
而我的XAML
DataGrid
代码:
<DataGrid AutoGenerateColumns="False" Name="studentsGrid" Margin="20" ItemsSource="{Binding}"
RowEditEnding="studentsGrid_RowEditEnding" AddingNewItem="studentsGrid_AddingNewItem" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding StudentId, NotifyOnSourceUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="StudentId" IsReadOnly="True" />
<DataGridTextColumn Binding="{Binding FirstName, NotifyOnSourceUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="First Name" />
<DataGridTextColumn Binding="{Binding Patronymic, NotifyOnSourceUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="Patronymic" />
<DataGridTextColumn Binding="{Binding LastName, NotifyOnSourceUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="Last Name" />
</DataGrid.Columns>
</DataGrid>
谁能帮我了解如何解决它?创建上下文以保存对数据库的更改。
谢谢。
我会尝试更改您的 XAML,以便
isInsertMode = true;
get在RowEditEnding事件触发时调用。你实际上调用它
添加新项目="studentsGrid_AddingNewItem"
这会导致触发,当您的模型此时甚至无法键入任何字符之前就没有任何数据时。您不能将"任何内容"保存到数据库中。您也可以通过在 isInsertMode = true 之前放置一个断点来检查这一点;呼唤它
studentsGrid_RowEditEnding()
确保数据库。当行失去焦点时,将调用保存更改。