首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

MySoft.Data 入門到精通(五):資料更新完整攻略

     編輯:關於.NET

承接前章資料新增,本章詳細說明 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
    }
}

一、強型別實體更新

1. 單一實體更新

var product = new Products { ProductID = 1, ProductName = "測試產品1" };
product.Attach(); // 標記為現有實體
DataAccess.ExampleSession.Save(product);

2. 批次更新

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();

3. 交易單一更新

using (var trans = DataAccess.ExampleSession.BeginTrans()) {
    try {
        product.Attach();
        trans.Save(product);
        trans.Commit();
    } catch { trans.Rollback(); }
}

4. 交易批次更新

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(); }
}

5. 外部連線更新

using (var conn = DataAccess.ExampleSession.CreateConnection()) {
    product.Attach();
    DataAccess.ExampleSession.SetConnection(conn).Save(product);
}

6. 外部交易更新

using (var trans = DataAccess.ExampleSession.BeginTransaction()) {
    try {
        product.Attach();
        DataAccess.ExampleSession.SetTransaction(trans).Save(product);
        trans.Commit();
    } catch { trans.Rollback(); }
}

二、InsertOrUpdate 智慧合併

var product = new Products { ProductID = 1, ProductName = "測試" };
DataAccess.ExampleSession.InsertOrUpdate(product); // 依主鍵判斷存在性自動切換

三、UpdateCreator 建構器更新

1. 實體驅動更新

var uc = UpdateCreator.NewCreator().From<Products>().SetEntity<Products>(product, true);
DataAccess.ExampleSession.Execute(uc);

2. 字串指定表/欄位

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)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved