我正在尝试在带有 Entity Framework 的 Wpf DataGrid上使用 CRUD 操作。现有行可以成功修改,并在单击保存按钮时保存更改。当涉及到新行时,实体框架 SaveChanges 出于某种原因不会保存新行。我认为这很容易,但我不明白这里做错了什么。
我在 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>
和这里显示的 ViewModel
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