I am trying to use a CRUD Operations on Wpf DataGrid with Entity Framework. Existing rows can successfully modified and when click save button changes are saved. When it comes to new rows the entity framework SaveChanges for some reason is not saving new rows. I thought that would be easy but I don't understand what am doing wrong here.
I have the following page in wpf
<Page x:Class="TaxGroupsListing"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:wendbooksVatRatSetup"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="TaxGroupsListing">
<Page.DataContext>
<local:TaxGroupListingVM x:Name="test"></local:TaxGroupListingVM>
</Page.DataContext>
<DockPanel >
<Button Margin="2" DockPanel.Dock="Top" Content="Load" Command="{Binding Path=LoadCmd}"></Button>
<Button Margin="2" DockPanel.Dock="Top" Content="Save" Command="{Binding Path=SaveCmd}"></Button>
<DataGrid IsSynchronizedWithCurrentItem="True" Margin="2" CanUserAddRows="True"
ItemsSource="{Binding Groups,UpdateSourceTrigger=PropertyChanged}">
</DataGrid>
</DockPanel>
And the ViewModel as shown here
Public Class TaxGroupListingVM : Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Sub notify()
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(String.Empty))
End Sub
Property Groups As New ObservableCollection(Of TaxGroup)
Property LoadCmd As New mycommad(AddressOf LoadData)
Property SaveCmd As New mycommad(AddressOf SaveData)
Private db As New SQlDataBaseEntities
Private Sub SaveData()
db.SaveChanges()
LoadData()
End Sub
Private Sub LoadData()
Dim qry = From g As TaxGroup In db.TaxGroups Select g
Groups = New ObservableCollection(Of TaxGroup)
For Each item In qry
Groups.Add(item)
Next
notify()
End Sub
End Class
When you add a new row, it's only adding a new item to the Groups collection, it's not adding the item to the DbContext.
When you add a new row, handle the CollectionChanged event of your Groups collection, and add the new items to the DbContext (something like db.TaxGroups.Add(newItem)). Then the db.SaveChanges should work fine.
(This probably should have been an answer to begin with, so adding it here instead of comment.)