2

我执行与EF 4.1存储库模式,http://huyrua.wordpress.com/2011/04/13/entity-framework-4-poco-repository-and-specification-pattern-upgraded-to-ef-4-1实体框架4.1,通用库和的ObservableCollection

我proble是,我在一个旧的WinForm应用程序正在工作,并以数据绑定返回的集合电网控制和检测新项目,我需要一个ObservableCollection,但是我在varios存储库模式中看到的所有存储库方法示例仅返回IList集合。

我现在要做的是:

IList<AccountType> accountTypes = _repository.GetAll<AccountType>().ToList(); 
var a1 = new AccountType { Name = "Bank2" }; 
var a2 = new AccountType { Name = "Cash2" }; 
accountTypes.Add(a1); 
accountTypes.Add(a2); 
_repository.UnitOfWork.SaveChanges(); 
Console.Write("AccountType Saved."); 

但与此代码,添加的项目不被库依然存在。

有人有任何想法如何避免这种情况,并返回一个BindigList或ObservableCollection使用EF 4.1的通用存储库?

编辑:

如果我转换的IList返回到ObservableColletion,你的意思somethink这样的测试代码,我写的是OK?:

[TestMethod] 
public void CreateAccountList() 
{ 
    _accountTypes = new ObservableCollection<AccountType>(_repository.GetAll<AccountType>().ToList()); 
    _accountTypes.CollectionChanged += CollectionChanged; 

    var a1 = new AccountType { Name = "Bank2" }; 
    var a2 = new AccountType { Name = "Cash2" }; 
    _accountTypes.Add(a1); 
    _accountTypes.Add(a2);   
    _accountTypes.Remove(a2); 
    _repository.UnitOfWork.SaveChanges(); 
    int count = _repository.Count<AccountType>(); 
    Assert.AreEqual(1, count); 
} 

void CollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) 
{ 
    switch (notifyCollectionChangedEventArgs.Action) 
    { 
     case NotifyCollectionChangedAction.Add: 
      foreach (var accountType in notifyCollectionChangedEventArgs.NewItems) 
      { 
       _repository.Add((AccountType)accountType);  
      }  
      break; 
     case NotifyCollectionChangedAction.Remove: 
      foreach (var accountType in notifyCollectionChangedEventArgs.OldItems) 
      { 
       _repository.Delete((AccountType)accountType); 
      } 
      break; 
    } 
} 

或者是有一个通用的方法做到这一点?

回答

1

为什么不能从存储库中获得IList,然后从这个列表中构建一个可观察的集合并且只使用它?

当您将它们添加到您从存储库获得的列表/集合中时,您不应该期望将这些元素添加到EF上下文中。您需要明确地调用存储库以保存/删除所需的元素,您将在存储库中添加和删除方法。

如果您想在UnitOfWork中“自动”执行此操作,那么UnitOfWork应该订阅集合的事件,以便知道集合何时更改,但看起来有点奇怪。