應用程式框架實戰十九:工作單元層超型別
阿新 • • 發佈:2018-12-29
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using Util.Datas.Ef.Exceptions;
using Util.Exceptions;
namespace Util.Datas.Ef {
/// <summary>
/// Entity Framework工作單元
/// </summary>
public abstract class EfUnitOfWork : DbContext, IUnitOfWork {
/// <summary>
/// 初始化Entity Framework工作單元
/// </summary>
/// <param name="connectionName">連線字串的名稱</param>
protected EfUnitOfWork( string connectionName )
: base( connectionName ) {
TraceId = Guid.NewGuid().ToString();
}
/// <summary>
/// 啟動標識
/// </summary>
private bool IsStart { get; set; }
/// <summary>
/// 跟蹤號
/// </summary>
public string TraceId { get; private set; }
/// <summary>
/// 啟動
/// </summary>
public void Start() {
IsStart = true;
}
/// <summary>
/// 提交更新
/// </summary>
public void Commit() {
try {
SaveChanges();
}
catch ( DbUpdateConcurrencyException ex ) {
throw new ConcurrencyException( ex );
}
catch ( DbEntityValidationException ex ) {
throw new EfValidationException( ex );
}
finally {
IsStart = false;
}
}
/// <summary>
/// 通過啟動標識執行提交,如果已啟動,則不提交
/// </summary>
internal void CommitByStart() {
if ( IsStart )
return;
Commit();
}
}
}