1
public static class DataTableHelper { public static List<T> ToModel<T>(this DataTable dt) where T : class ,new() { if (dt == null || dt.Rows.Count == 0) return null; Type type = typeof(T); var list = new List<T>(); for (int row = 0; row < dt.Rows.Count; row++) { Object obj = type.Assembly.CreateInstance(type.FullName); System.Reflection.PropertyInfo[] Props = typeof(T).GetProperties(); for (int i = 0; i < Props.Length; i++) { if (Props[i].CanWrite && dt.Columns.IndexOf(Props[i].Name) > -1) { Props[i].SetValue(obj, dt.Rows[row][Props[i].Name], null); } } list.Add(obj as T); } return list; } } public class StudentModel { public int Id { get; set; } public string Name { get; set; } public DateTime CreateTime { get; set; } } //数据库访问对象 public class Studuent { public static IList<StudentModel> GetList() { //不允许脏读 string sql = "SELECT Id,Name,CreateTime FROM Student ORDER BY Id DESC;"; DataTable dt = SqlHelper.Instance.ExecuteDataTable(CommandType.Text, sql); return dt.ToModel<StudentModel>(); } public static bool Add(string name) { SqlParameter[] parms = { new SqlParameter("@Name", SqlDbType.NVarChar, 32) { Value = name }, new SqlParameter("@CreateTime", SqlDbType.DateTime) { Value = DateTime.Now } }; string sql = "INSERT INTO Student (Name,CreateTime) VALUES (@Name,@CreateTime)"; return SqlHelper.Instance.ExecuteNonQuery(CommandType.Text, sql, parms) > 0; } public static void Clear() { SqlHelper.Instance.ExecuteNonQuery("DELETE From Student"); } //公共方法,输出学生列表 } public class TransactionScopeTest { static void PrintStudent() { IList<StudentModel> list = Studuent.GetList(); if (list == null) return; foreach (var item in list) { Console.WriteLine("{0}\t{1}\t{2}", Thread.CurrentThread.ManagedThreadId, item.Name, item.CreateTime); } Console.WriteLine(); } public static void Excute() { Studuent.Clear(); Task.Run(() => { Console.WriteLine("开始添加用户"); using (TransactionScope scope = new TransactionScope()) { Studuent.Add("Grace"); Studuent.Add("Aven"); scope.Complete(); //在Compltete已提交数据库 Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "Scope已提交"); Thread.Sleep(1000 * 10); } //在作用范围外解除锁表 Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "scope已释放"); }); //PrintStudent(); } }
时间: 2024-10-10 01:55:25