PetaPoco更新了winforms中的修改记录

我有这个代码:

namespace PetaPocoTest { public partial class Form1 : Form { PetaPoco.Database db = new PetaPoco.Database("PgConnection"); IEnumerable allCustomers; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { allCustomers = db.Query("SELECT * FROM customers"); mGrid.DataSource = allCustomers .ToList(); } private void saveButton_Click(object sender, EventArgs e) { foreach (var a in allCustomers) { db.Save("customers", "custumer_id", a); } } } } 

bat这会更新所有记录,无论它们是否被更改。 所以,我的问题是,是否有人知道如何仅更新petapoco中已更改的记录?

这就是我做到的(最终!):

 namespace PetaPocoTest { public partial class Form1 : Form { PetaPoco.Database db = new PetaPoco.Database("PgConnection"); Dictionary modRows = new Dictionary(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { bindingSource = db.Fetch("SELECT * FROM customers"); mGrid.DataSource = bindingSource; } private void saveButton_Click(object sender, EventArgs e) { db.BeginTransaction(); foreach (customers c in bindingSource) { if (modRows.ContainsKey(c.id.ToString())) { db.Save("customers", "id", c); } } db.CompleteTransaction(); } private void mGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e) { int recId = ((customers)bindingSource.Current).id; if (!modRows.ContainsKey(recId.ToString())) { modRows.Add(recId.ToString(), recId); } } } } 

它的function,但如果有人有更好的想法请分享!

这是我通过Form_Load上的db.BeginTransaction执行此操作的最简单方法

  private void Form1_Load(object sender, EventArgs e) { studentBindingSource.DataSource = db.Query("SELECT * FROM student"); db.BeginTransaction(); // Begin Transaction here } 

更新CellValueChanged )上只是简单地做db.Save()这还没有提交,因为我们的事务尚未完成

  private void studentDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) { db.Save((student)studentBindingSource.Current); } 

是的,我们也可以做插入删除

插入

 private void buttonInsert_Click(object sender, EventArgs e) { student newStudent = new student { StudentName = "POCONEW" } studentBindingSource.Add(newStudent); db.Save(newStudent); } 

删除

 private void studentDataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) { int rowIndex = e.Row.Index; // We use Gridview row index instead because BindingSource.Current isn't work when user drag then deleting multiple row db.Delete(studentDataGridView.Rows[rowIndex].DataBoundItem as student); } 

最后为了保存更改,我们只做db.CompleteTransaction() :在用户按下保存按钮之后,如果你没有关闭表单,只需要注意一点,如果不是用户编辑之后所有用户都要调用db.BeginTransaction()由于我们不再拥有交易,因此会自动保存

 private void btSave_Click(object sender, EventArgs e) { db.CompleteTransaction(); db.BeginTransaction(); // everything user edit after this will be saved automatically because we don't have Transaction anymore so we Begin it again }