我正在对复杂的.NET数据库进行一些测试,为了回滚用户所做的更改,我需要得到一些建议。例如,让我们假设我的BL层中有两个类:
" person“代表核心person对象:
internal class Person{
public String Name{get; set;}
public String Surname{get; set;}
public int Age { get; set; }
}
"PeopleList“表示person对象的列表:
internal class PeopleList : List<Person> {
//Let's assume that this class has a whole bunch of function with a complex business logic in it.
public Person[] getPeopleByName(String name)
{
return this.Where(x => String.Compare(name, x.Name, true) == 0).ToArray();
}
public Person[] getPeopleByAge(int age)
{
return this.Where(x => x.Age.Equals(age)).ToArray();
}
}
现在,我想让用户通过带有PeopleList的表单编辑DataGridView对象的实例。因此,我创建了一个windows窗体应用程序,并在Load()事件中执行了以下操作:
private void frmTest_Load(object sender, EventArgs e)
{
//Intialize _peopleList object
_peopleList = new PeopleList();
this.initializePeopleWithTestData();
//Initialize _peopleBindingList by passing PeopleList (it inherits from List<Of ?> and it implements IList interface)
this._peopleBindingList = new BindingList<Person>( _peopleList);
//Initialize _peopleBindingSource
this._peopleBindingSource = new BindingSource();
this._peopleBindingSource.DataSource = this._peopleBindingList;
this._peopleBindingSource.SuspendBinding(); //Let's suspend binding to avoid _peopleList to be modified.
//Set peopleBindingList as DataSource of the grid
this.dgwPeople.DataSource = _peopleBindingSource;
}
使用上述代码,我可以看到/编辑/删除/添加dgwPeople中的人员(这是我的数据视图),但即使我在BindingSource上调用了"SuspendBinding()“,如果用户编辑网格,绑定系统也会立即影响到包含到SuspendBinding对象中的数据!这是不好的,因为这样我就失去了原始版本的数据,如果用户决定取消更改,我就不能再回滚它们了。
在简单的绑定中,有一个奇妙的属性"DataSourceUpdateMode“,可以让我决定绑定何时必须影响数据源。如果将其设置为“从不”,则必须显式调用Write()方法来提交更改。对于复杂的绑定有类似的东西吗?
如何避免在复杂绑定中立即绑定以影响原始数据?是否有任何方法回滚更改(除了保留原始对象的克隆副本)?有什么模式可以帮助处理这种情况吗?
您可以下载我的测试解决方案(VS2012) 这里
提前感谢!
发布于 2013-11-30 06:35:24
internal class Person, iNotifyPropertyChanged
{
// todo implement NotifyPropertyChanged
private string name;
private string nameOrig;
public String Name
{
get {return name; }
set
{
if (name == value) return;
name = value;
NotifyPropertyChanged("Name");
}
}
public void RollBack() { Name = nameOrig; }
public void CommitChanges() { nameOrig = name; }
public Person (string Name) { name = Name; nameOrig = name; }
}
https://stackoverflow.com/questions/20301014
复制相似问题