我正在尝试将我的ViewModel上的更改传播到实体框架,但我很难理解如何执行此操作。我的实体框架中的所有实体都实现了INotifyPropertyChanged。这是我的VM类:
Imports System.Collections.ObjectModel
Imports System.ComponentModel
Public Class MainWindowVM
Implements INotifyPropertyChanged
Dim dbcontext As New FootballPoolEntities
Private _Users As ObservableCollection(Of User)
Private _Settings As ObservableCollection(Of ScheduleSetting)
Public Property Users As ObservableCollection(Of User)
Get
Return _Users
End Get
Set(value As ObservableCollection(Of User))
_Users = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Users"))
End Set
End Property
Public Property Settings As ObservableCollection(Of ScheduleSetting)
Get
Return _Settings
End Get
Set(value As ObservableCollection(Of ScheduleSetting))
_Settings = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Settings"))
End Set
End Property
Public Sub New()
'dbcontext = New FootballPoolEntities
_Users = New ObservableCollection(Of User)(dbcontext.Users.ToList)
_Settings = New ObservableCollection(Of ScheduleSetting)(dbcontext.ScheduleSettings.ToList)
End Sub
Public Sub Save()
dbcontext.SaveChanges()
End Sub
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
End Class
我知道我现在需要使用collectionchanged事件将这些更改更新到我的dbcontext,但目前还不清楚如何实现它。
非常感谢任何指导。
答案 0 :(得分:1)
通常,我们的应用程序中有三个主要层; UI(视图),视图模型和数据库访问。视图通常包含TextBox
等等,供用户输入或编辑值,并保存Button
以保存更改。因此,保存数据以响应Button Command
比响应CollectionChanged
事件更为常见。
因此,您的视图模型是定义Command
的位置(如果您使用某种delegate Command
),应该有权访问数据库访问层。因此,做这样的事情通常很简单,就是保存数据:
public ICommand SaveCommand
{
get { return new ActionCommand(action => Save(),
canExecute => CanSave(AudioTrack)); }
}
...
private void Save()
{
if (AudioTrack.IsNew) Model.AddAudioTrack(AudioTrack);
else Model.UpdateAudioTrack(AudioTrack);
}
答案 1 :(得分:0)
我需要做的是为CollectionChanged事件添加一个处理程序,该事件从dbcontext集合中添加新的或删除的已删除对象。
Private Sub OnUsersCollectionChanged(sender As Object, e As NotifyCollectionChangedEventArgs)
If e.Action = NotifyCollectionChangedAction.Add Then
For Each item In e.NewItems
dbcontext.Users.Add(item)
Next
End If
If e.Action = NotifyCollectionChangedAction.Remove Then
For Each item In e.OldItems
dbcontext.Users.Remove(item)
Next
End If
End Sub
然后我在sub new()
中添加了一个处理程序AddHandler Users.CollectionChanged, AddressOf OnUsersCollectionChanged