老赵的博客:
1、DataContext扩展方法
public static class DataContextExentions { ////// 打开连接 /// /// private static void OpenConnection(this DataContext dataContext) { if (dataContext.Connection.State == ConnectionState.Closed) { dataContext.Connection.Open(); } } ////// 扩展ExecuteQuery方法 /// ////// /// /// /// public static List ExecuteQuery (this DataContext dataContext, IQueryable query, bool withNoLock) { DbCommand command = dataContext.GetCommand(query, withNoLock); dataContext.OpenConnection(); using (DbDataReader reader = command.ExecuteReader()) { return dataContext.Translate (reader).ToList(); } } /// /// 扩展ExecuteQuery方法2 /// ////// /// /// /// public static List ExecuteQuery (this DataContext dataContext, IQueryable query) { DbCommand command = dataContext.GetCommand(query); dataContext.OpenConnection(); using (DbDataReader reader = command.ExecuteReader()) { return dataContext.Translate (reader).ToList(); } } /// /// 扩展GetCommend方法,允许设置WithNoLick /// /// /// /// ///private static SqlCommand GetCommand(this DataContext dataContext, IQueryable query, bool withNoLock) { SqlCommand command = (SqlCommand)dataContext.GetCommand(query); if (withNoLock) { command.CommandText = AddWithNoLock(command.CommandText); } return command; } /// /// 将Sql语句修改为with nolock /// /// ///private static string AddWithNoLock(string cmdText) { IEnumerable matches = s_withNoLockRegex.Matches(cmdText).Cast () .OrderByDescending(m => m.Index); foreach (Match m in matches) { int splitIndex = m.Index + m.Value.Length; cmdText = cmdText.Substring(0, splitIndex) + " WITH (NOLOCK)" + cmdText.Substring(splitIndex); } return cmdText; } private static Regex s_withNoLockRegex = new Regex(@"(] AS [td+])", RegexOptions.Compiled); }}
2、DataContext扩展方法支持分页
////// DataContext扩展方法/// public static class DataContextExtends{ ////// ExecuteQuery方法扩展,将对象以redader方式转换为实体 /// ////// /// /// public static List ExecuteQuery (this DataContext dataContext, IQueryable