BaseDBContext
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.EntityClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MIS.User_Mapping.Wcf.Shared { public class BaseDBContext : DbContext { public BaseDBContext(string connNameOrConnStr) : base(connNameOrConnStr) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer<BaseDBContext>(null); base.OnModelCreating(modelBuilder); } #region DataBase private DbConnection conn = null; public void Connect() { if (conn == null) { conn = ((IObjectContextAdapter)this).ObjectContext.Connection; } if (conn.State == ConnectionState.Closed) { conn.Open(); } else if (conn.State == ConnectionState.Broken) { conn.Close(); conn.Open(); } } public void Disconnect() { if (conn.State != ConnectionState.Closed) { conn.Close(); conn = null; } } #endregion #region Tran /// <summary> /// CurTran /// </summary> public EntityTransaction CurTran { get; private set; } /// <summary> /// BeginTran /// </summary> /// <param name="isolationLevel"></param> public void BeginTran(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted) { Connect(); if (CurTran == null) { CurTran = conn.BeginTransaction(isolationLevel) as EntityTransaction; } } /// <summary> /// CommitTran /// </summary> public void CommitTran() { if (CurTran != null) { CurTran.Commit(); CurTran.Dispose(); CurTran = null; } } /// <summary> /// RollBackTran /// </summary> public void RollBackTran() { if (CurTran != null) { CurTran.Rollback(); CurTran.Dispose(); CurTran = null; } } #endregion protected override void Dispose(bool disposing) { if (conn != null) { conn.Dispose(); conn = null; } base.Dispose(disposing); GC.SuppressFinalize(this); } ~BaseDBContext() { this.Dispose(); } } }