I am struggling with updating existing lecturer data in a database.
Each teacher has a Name , AcademicDegree and the Courses that are taught to them (Courses == Lessons).
There are actually more properties in class Lecturer , but they are not relevant. For simplicity, suppose the POCO class is defined as follows:
In the data access layer, I have a void UpdateLecturer(Lecturer lecturer) method that should update the lecturer whose Id_Lecturer is equal to lecturer.Id_Lecturer (using lecturer.Name , lecturer.AcademicDegree and lecturer.Courses ).
This is a very convenient method, because in ViewModel I can call _dataAccess.UpdateLecturer(SelectedLecturer) (where SelectedLecturer bound in XAML ; SelectedLecturer properties can be set by the user in TextBox es and Checkbox ).
Unfortunately, this method:
public void UpdateLecturer(Lecturer lecturer) { using(var db = new AcademicTimetableDbContext()) {
updates everything ( Id_Lecturer , Name , Academic_Degree_Id and AcademicDegree ) except Courses , which do not change after db.SaveChanges() .
Why? How can i fix this?
Similar issues:
- Change -
I also tried this way (idea came from this post ):
public void UpdateLecturer(Lecturer lecturer) { using (var db = new AcademicTimetableDbContext()) { if (lecturer == null) return; DbEntityEntry<Lecturer> entry = db.Entry(lecturer); if (entry.State == EntityState.Detached) { Lecturer attachedEntity = db.Set<Lecturer>().Find(lecturer.Id_Lecturer); if (attachedEntity == null) entry.State = EntityState.Modified; else db.Entry(attachedEntity).CurrentValues.SetValues(lecturer); } db.SaveChanges(); } }
but still, courses do not overwrite old values.
- Change 2 -
In response to a @Slauma question, I will describe how I loaded SelectedLecturer (which is passed to UpdateLecturer(Lecturer lecturer) as an argument).
I am implementing the MVVM concept, so I have a View project in my solution with the DataContext set to LecturerListViewModel . The view has a DataGrid with a list of all the lecturers extracted from the database. DataGrid bound as follows:
<DataGrid AutoGenerateColumns="False" Name="LecturersDataGrid" HeadersVisibility="Column" IsReadOnly="True" ItemsSource="{Binding Lecturers,Mode=TwoWay}" SelectedItem="{Binding SelectedLecturer, Mode=TwoWay}"> <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="{Binding Name}" /> <DataGridTextColumn Header="Academic degree" Binding="{Binding AcademicDegree.Degree_Name}" /> <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <Button Content="Edit" Click="EditButtonClick"/> <Button Content="Delete" Command="{Binding DataContext.RemoveLecturer, ElementName=LecturersDataGrid}" /> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid>
Lecturers are retrieved from the database in the LecturerListViewModel constructor as follows: