2013-02-19 47 views
1

我想在我的WPF项目上使用实体框架获取/操作数据来实现MVVM模式。 我很困惑,我想知道在哪里验证我的模型对象集合到数据库的变化应该是? 我的应用程序如下:在我看来,我有一个人的数据网格,两个文本框,将加载所选人员的姓名,一个按钮更新行更改和一个按钮删除选定的行。使用实体框架实现MVVM模式 - 添加删除

在我的ModelView中,我有一个observableCollection,它将在我的数据库(实体)+两个用于添加/删除按钮的继电器命令(请查看下面的代码)的类初始化时加载。

的问题是,我不明白MVVM,何时何地以及如何对我的数据的修改应推到数据库的良好的理念是什么? 现在,当我更新我的数据库中的一行,并且将我的数据库上下文修改保存在我的observable集合上时,但是当我删除一个项目时它不是cdase,我必须在数据库中手动查找它并将其删除(我已经将我的observablecollection附加到一个NotifyCollectionChangedEventHandler事件来处理这个事件)...我没有明白使用Observable集合的意义!

是否有使用数据库中的数据“完美”的MVVM架构的任何简单的解释??? 谢谢! 我的ViewModel

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Collections.ObjectModel; 
using System.Windows.Data; 
using System.ComponentModel; 
using System.Windows.Input; 
using System.Windows; 
using MVVMOK.Models; 
using MVVMOK.Base; 
using System.Collections.Specialized; 

namespace MVVMOK.ViewModel 
{ 
    class MainWindowViewModel : ViewModelBase 
    { 
     private DW_MargoEntities contexte; 



     //Constructor 
     public MainWindowViewModel() 
     { 
      contexte = new DATABASEEntities(); 
      collectionOfCollaborators = new ObservableCollection<Collaborator>(); 
      foreach (Collaborator c in contexte.Collaborator) 
      { 
       collectionOfCollaborators.Add(c); 
      } 


      //Abonnement pour l'ajout ou la suppression d'éléments : 
      collectionOfCollaborators.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(collectionOfCollaboratorsChanged); 

      //Assignation des commandes : 
      this._deleteComand = new RelayCommand(new Action<object>(DeleteRow)); 
      this._updateCommand = new RelayCommand(new Action<object>(UpdateDB)); 
     } 
     //liste des propriétés publiques: 


     //Propriété pour représenter l'élément séléctionné du datagrid 
     private Collaborator selectedItem; 
     public Collaborator _selectedItem 
     { 
      get { return selectedItem; } 
      set 
      { 
       if (value != selectedItem) 
       { 
        selectedItem = value; 
        OnPropertyChanged("_selectedItem"); 
       }; 
      } 
     } 
     //Propriété pour représenter l'élément séléctionné: 
     private ObservableCollection<Collaborator> collectionOfCollaborators; 
     public ObservableCollection<Collaborator> _collectionOfCollaborators 
     { 
      get { return collectionOfCollaborators; } 
      set 
      { 
       this.collectionOfCollaborators = value; 
       OnPropertyChanged("_collectionOfCollaborators"); 
      } 
     } 

     //Commandes : 
     public ICommand _updateCommand 
     { 
      get; 
      set; 
     } 
     public ICommand _deleteComand 
     { 
      get; 
      set; 
     } 

     void collectionOfCollaboratorsChanged(object sender, NotifyCollectionChangedEventArgs e) 
     { 
      Collaborator f = new Collaborator(); 
      switch (e.Action) 
      { 
       case NotifyCollectionChangedAction.Add: 

        for(int i = 0; i<e.NewItems.Count;i++) 
        { 

         if (e.NewItems[i].GetType().Equals(f.GetType())) 
         { 
          contexte.Collaborator.Add(e.NewItems[i] as Collaborator); 
         } 
        } 
        contexte.SaveChanges(); 
        break; 

       case NotifyCollectionChangedAction.Remove: 

        for (int i = 0; i < e.OldItems.Count; i++) 
        { 

         if (e.OldItems[i].GetType().Equals(f.GetType())) 
         { 
          contexte.Collaborator.Remove(e.OldItems[i] as Collaborator); 
         } 
        } 
        contexte.SaveChanges(); 
        break; 
       //Reset = Clear 

      } 
     } 



     //Services : 
     public void UpdateDB(object msg) 
     { 
      contexte.SaveChanges(); 
     } 


     public void DeleteRow(object msg) 
     { 

      _collectionOfCollaborators.Remove(_selectedItem); 
      contexte.SaveChanges(); 
     } 
    } 
} 

我的模型

namespace MVVMOK.Models 
{ 
    using System; 
    using System.Collections.Generic; 

    public partial class Collaborator 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public string Surname { get; set; } 
    } 
} 

我的XAML

<Window x:Class="MVVMOK.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:MVVMOK.ViewModel" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.DataContext> 
     <!-- Declaratively create an instance of our SongViewModel --> 
     <local:MainWindowViewModel /> 
    </Window.DataContext> 
    <Grid> 
     <Grid Height="237" HorizontalAlignment="Left" Margin="12,12,0,0" Name="grid1" VerticalAlignment="Top" Width="479"> 
      <DataGrid AutoGenerateColumns="False" Height="237" HorizontalAlignment="Left" Name="dataGrid1" VerticalAlignment="Top" Width="479" ItemsSource="{Binding Path=_collectionOfCollaborators, Mode=TwoWay}" SelectionMode="Single" SelectedItem="{Binding Path=_selectedItem, Mode=TwoWay}" > 
       <DataGrid.Columns> 
        <DataGridTextColumn Binding="{Binding Path=Id}" Header="ID" /> 
        <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" Width="4*" /> 
       </DataGrid.Columns> 
      </DataGrid> 
     </Grid> 
     <TextBox Height="23" HorizontalAlignment="Left" Margin="104,255,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text ="{Binding Path=_selectedItem.Name, Mode=TwoWay}" /> 
     <TextBox Height="23" HorizontalAlignment="Left" Margin="104,283,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" Text ="{Binding Path=_selectedItem.Surname, Mode=TwoWay}" /> 
     <Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="50,255,0,0" Name="label1" VerticalAlignment="Top" /> 
     <Label Content="Surname" Height="28" HorizontalAlignment="Left" Margin="37,283,0,0" Name="label2" VerticalAlignment="Top" /> 
     <Button Content="Delete Row" Height="23" HorizontalAlignment="Left" Margin="416,260,0,0" Name="button1" VerticalAlignment="Top" Width="75" Command="{Binding Path=_deleteComand}"/> 
     <Button Content="Update All" Height="23" HorizontalAlignment="Left" Margin="335,260,0,0" Name="button2" VerticalAlignment="Top" Width="75" Command="{Binding Path=_updateCommand}"/> 
    </Grid> 
</Window> 

回答

0

我觉得这是不是 “” 方式MVVM总有几个和像往常一样,它依赖。

但到解决方案中有一个名为IDataErrorInfo它可以帮助你的接口。

对于一个例子来看看这篇文章...... http://www.codeproject.com/Articles/98681/Validating-User-Input-WPF-MVVM

或者在这里: http://blindmeis.wordpress.com/2012/04/16/wpf-mvvm-idataerrorinfo-validation-errortemplate/

也许你应该考虑从您的视图模型隐藏实体框架与存储库模式或只需DataService

希望帮助...

1

我没有回答,为什么你没有看到您预期的结果,但我想我会给你如何构建这个好一点的一些想法。

当数据更改应用命令时,您真正想要做什么。例如,应该应用删除命令。处理这个命令时,你可以执行任何验证,并保持更改或标记错误。因此,您在Relay命令中包装的DeleteRow类应该是应用程序模型层中的单独类。 您可以有一个使用MVVM的Web层,但它应该是持久性无知的,它应该应用一个命令,然后在命令成功或失败时做出适当的反应。

this._deleteComand = new RelayCommand(new Action<object>(DeleteRow)); 

可能是更多的东西一样

this._deleteComand = new RelayCommand(new Action<object>() => {new DeleteCommandHandler().Apply(new DeleteCommand(){SelectedItem = _selectedItem})}); 

的DeleteCommandHandler和DeleteCommand会形成模型的一部分(我会用不同的类库这一点)。

现在您的处理程序需要了解您的持久性机制,因此您的处理程序中可以创建DW_MargoEntities上下文并执行删除工作。

这样做的好处是您的视图模型不再负责更新您的模型,因此您的视图模型将会简单得多,并且不会直接依赖于您使用的数据库。

一旦你有一个命令处理程序模式设置,我会转向你的上下文的依赖注入。例如,如果不是说说新的DeleteCommandHandler(),你可以要求一个反转控制容器,比如结构图来构建它。

ObjectFactory.GetInstance<DeleteCommandHandler>(); 

然后你DeleteCommandHandler类可能看起来像

class DeleteCommandHandler 
{ 
    DW_MargoEntities context; 
    public DeleteCommandHandler(DW_MargoEntities context) 
    { 
     this.context = context; 
    } 

    public bool Apply(DeleteCOmmand command) 
    { 
     if (not valid) {return false;} 
     var item = context.LoadEntityById<EntityTypeHere>(command.SelectedItem) // Query the item 

     context.Delete(item); 
     return true; 
    } 
} 

对不起,我是一个有点模糊,这是一个很多解释和它的晚在这里变得有点。阅读命令模式http://en.wikipedia.org/wiki/Command_pattern

+2

实际上,为什么我没有看到结果是因为ObservableCollection仅在更新元素(如我在某些论坛和讨论中看到的)时才通知,而不是在添加或删除实体时通知... The MSDN文档真的很模糊! – Mohtaa 2013-02-19 12:20:51