C# 采用事务批量插入数据

首先要构建一个实体类,注意实体类的属性和数据的列要一一对应,否则会报错。

public class Animal
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int Weight { get; set; }
        public string Color { get; set; }

    }

 根据实体类获取要插入的表结构

   public static string GetProperty<T>(T t)
         {
             string str=String.Empty;
             StringBuilder sb = new StringBuilder();
             if (t == null)
             {
                 return str;
             }
             System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties();
             if (properties.Length <= 0)
             {
                 return str;
             }
             foreach (System.Reflection.PropertyInfo info in properties)
             {
                 sb.Append(string.Format("@{0},", info.Name));
             }
             sb.Remove(sb.Length-1,1);
             return sb.ToString();
         }

数据插入的方法:

 public int InsertBatch<T>(IEnumerable<T> entities)
        {
            Type t = typeof(T);
            string sql = "insert into " + t.Name + " values ("+ClassHelper.GetProperty(entities.FirstOrDefault())+")";
            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConnectionString))
            {
                conn.Open();
                int records = 0;
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        records = conn.Execute(sql, entities, trans, 30, CommandType.Text);
                    }
                    catch (DataException ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                    trans.Commit();
                }
                return records;
            }
        }   


 

 

posted @ 2016-08-09 10:17  止水的水  阅读(1304)  评论(0编辑  收藏  举报