【发布时间】:2015-01-15 12:31:12
【问题描述】:
我是一名新的 WPF 开发人员,正在为一家旅馆编写 WPF 项目。我将实体框架与 DB 优先方法一起使用。在 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>
谁能帮我理解如何解决它?制作上下文以保存对数据库的更改。
谢谢。
【问题讨论】:
-
我知道您说您没有收到任何错误,但是将
SaveChanges()包装在try..catch块中,看看发生了什么。 -
@Ric 成功了,一切顺利,没有错误
-
在添加实体但不更新时是否有效?
-
@Ric 不,这两种情况都不起作用
标签: c# wpf datagrid frameworks entity