/*-------------LINQ to SQL框架入口System.Data.Linq.DataContext初始化(初始化数据库连接、打开连接、事务开启等)-------------*/ /// <summary> /// 获取数据库上下文 /// </summary> /// <param name="attr"></param> /// <returns></returns> private SqlDataContext GetDataContext(BusinessMethodAttribute attr) { SqlDataContext dataContext = new SqlDataContext(this.ReaderConnectionString(), new DynamicMappingSource()); dataContext.ObjectTrackingEnabled = false; dataContext.Log = Console.Out; dataContext.Connection.Open(); DbTransaction trans = null; var attrTrans = attr.Transaction; if (attrTrans != Transaction.None) { trans = attrTrans == Transaction.Lock ? dataContext.Connection.BeginTransaction() : attrTrans == Transaction.WithNoLock ? dataContext.Connection.BeginTransaction(IsolationLevel.ReadUncommitted) : dataContext.Connection.BeginTransaction(IsolationLevel.ReadUncommitted); } dataContext.Transaction = trans; // dataContext.DataTableChanged.Clear(); return(dataContext); }
/// <summary> /// 方法调用开始--注入SqlDataContext对象 /// </summary> internal void MethodBegin(IMessage msg, IMethodReturnMessage methodReturnMsg, BusinessMethodAttribute attr) { //注入SqlDataContext对象到业务基类 this._DataContext = this.GetDataContext(attr); //注入dao到业务基类--用注入的SqlDataContext对象,反射初始化业务子类方法中字段或属性的dao Type type = this.GetType(); BindingFlags bf = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; FieldInfo[] fi = type.GetFields(bf).Where(p => p.FieldType.GetInterface("BusinessProxy.ITemplateBaseDao") != null).ToArray(); PropertyInfo[] pi = type.GetProperties().Where(p => p.PropertyType.GetInterface("BusinessProxy.ITemplateBaseDao") != null).ToArray(); //字段中的dao foreach (var item in fi) { ITemplateBaseDao dao = item.GetValue(this) as ITemplateBaseDao; if (dao == null) { dao = Activator.CreateInstance(item.FieldType) as ITemplateBaseDao; item.SetValue(this, dao); } if (dao != null) { dao.DataContext = this._DataContext; } } //属性中的dao foreach (var item in pi) { ITemplateBaseDao dao = item.GetValue(this, null) as ITemplateBaseDao; if (dao == null) { dao = Activator.CreateInstance(item.PropertyType) as ITemplateBaseDao; item.SetValue(this, dao); } if (dao != null) { dao.DataContext = this._DataContext; } } }