2015-10-29 90 views
2

我正在嘗試使用Wpf DataGrid與實體框架的CRUD操作。 現有行可以成功修改,並且保存單擊保存按鈕更改時。當涉及新行時,實體框架SaveChanges出於某種原因不保存新行。我認爲這很容易,但我不明白這裏做錯了什麼。如何使用實體框架從DataGrid更新數據庫

,我有以下頁面中的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> 

而視圖模型如下圖所示

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 

回答

1

當你添加一個新行,它只是增加一個新項Groups集合,它不會將項目添加到DbContext。

當您添加新行時,處理您的Groups集合的CollectionChanged事件,並將新項目添加到DbContext(類似db.TaxGroups.Add(newItem))。然後db.SaveChanges應該可以正常工作。

(這大概應該已經開始與一個答案,所以這裏將其添加的,而不是評論。)

+0

謝謝,我想過這個,之前我看了你的答案我嘗試用這種方式,而是讓我只是爲了好奇才問你一些事情。 由於實體框架是一種較新的技術,不應該立即提供此功能嗎? 我的意思是在DataTables中 - DataViews這個功能已經存在,如果你設置了正確的變量CommandBuilders等等。新的行或刪除的行會自動更新。 – user2160275

+0

那麼我知道有一些第三方庫確實具有這種類型的集成(例如DevExpress),但我個人不希望.NET DataGrid具有此功能。它會在DataGrid和EF之間創建一個不需要的依賴關係,IMO。但是,自己繼承並實現它並沒有太多的工作,這樣,DbContext和DataGrid之間的依賴關係就會成爲您自己的(甚至是在數據源集合中)。很高興你的工作雖然。 –

相關問題