承接前章資料新增,本章詳細說明 DbSession 執行資料更新的六種模式與進階技巧。
public static class DataAccess {
public static readonly DbSession DefaultSession = new DbSession("DataExample");
public static readonly DataExample ExampleSession = new DataExample();
}
public class DataExample : DbSession {
public DataExample() : base("DataExample") {
#if DEBUG
this.RegisterSqlLogger(log => File.WriteAllText(@"c:\log.txt", log));
#endif
}
}
var product = new Products { ProductID = 1, ProductName = "測試產品1" };
product.Attach(); // 標記為現有實體
DataAccess.ExampleSession.Save(product);
var list = Enumerable.Range(0, 10).Select(i => new Products { ProductID = i, ProductName = "測試" + i }).ToList();
var batch = DataAccess.ExampleSession.BeginBatch(10);
list.ForEach(item => { item.Attach(); batch.Save(item); });
batch.Process();
using (var trans = DataAccess.ExampleSession.BeginTrans()) {
try {
product.Attach();
trans.Save(product);
trans.Commit();
} catch { trans.Rollback(); }
}
using (var trans = DataAccess.ExampleSession.BeginTrans()) {
try {
var batch = trans.BeginBatch(10);
list.ForEach(item => { item.Attach(); batch.Save(item); });
batch.Process();
trans.Commit();
} catch { trans.Rollback(); }
}
using (var conn = DataAccess.ExampleSession.CreateConnection()) {
product.Attach();
DataAccess.ExampleSession.SetConnection(conn).Save(product);
}
using (var trans = DataAccess.ExampleSession.BeginTransaction()) {
try {
product.Attach();
DataAccess.ExampleSession.SetTransaction(trans).Save(product);
trans.Commit();
} catch { trans.Rollback(); }
}
var product = new Products { ProductID = 1, ProductName = "測試" };
DataAccess.ExampleSession.InsertOrUpdate(product); // 依主鍵判斷存在性自動切換
var uc = UpdateCreator.NewCreator().From<Products>().SetEntity<Products>(product, true);
DataAccess.ExampleSession.Execute(uc);
var uc = UpdateCreator.NewCreator()
.From("Products")
.AddUpdate("ProductName", "測試產品")
.AddWhere("ProductID", 1);
DataAccess.ExampleSession.Execute(uc);
var where = Where.All;
if (cond1) where &= Products._.ProductID == 1;
if (cond2) where &= Products._.ProductID == 2;
if (cond3) where |= Products._.ProductID.In(1, 2); // IN
if (cond4) where |= !Products._.ProductID.In(1, 2); // NOT IN
DataAccess.ExampleSession.Update<Products>(Products._.ProductName, "測試", where);
以上皆可搭配交易:trans.Execute(uc)。