时间:2021-07-01 10:21:17 帮助过:20人阅读
然后定义一个与表映射的Model,因SqlBulkCopy 的特性,定义的 Model 必须拥有与表所有的字段对应的属性:也就是定义的model,需要跟数据表的字段顺序一样,因为转为datatable时会按照顺序插入
1 public enum Gender 2 { 3 Man = 1, 4 Woman 5 } 6 7 public class User 8 { 9 public Guid Id { get; set; } 10 public string Name { get; set; } 11 public Gender? Gender { get; set; } 12 public int? Age { get; set; } 13 public int? CityId { get; set; } 14 public DateTime? OpTime { get; set; } 15 }
制造些数据转为DataTable:
List转为DataTable地址:https://www.cnblogs.com/zhangShanGui/p/12038563.html
1 List<User> usersToInsert = new List<User>(); 2 usersToInsert.Add(new User() { Id = Guid.NewGuid(), Name = "so1", Gender = Gender.Man, Age = 18, CityId = 1, OpTime = DateTime.Now }); 3 usersToInsert.Add(new User() { Id = Guid.NewGuid(), Name = "so2", Gender = Gender.Man, Age = 19, CityId = 2, OpTime = DateTime.Now }); 4 usersToInsert.Add(new User() { Id = Guid.NewGuid(), Name = "so3", Gender = Gender.Man, Age = 20, CityId = 3, OpTime = DateTime.Now }); 5 usersToInsert.Add(new User() { Id = Guid.NewGuid(), Name = "so4", Gender = Gender.Man, Age = 21, CityId = 4, OpTime = DateTime.Now }); 6 7 var data = DataTableExtensions.ToDataTable(usersToInsert); 8 using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnectionString)) 9 { 10 bulkCopy.DestinationTableName = 11 "Users"; 12 try 13 { 14 bulkCopy.WriteToServer(data, DataRowState.Added); 15 } 16 catch (Exception ex) 17 { 18 Console.WriteLine(ex.Message); 19 } 20 }
sqlserver数据库批量插入-SqlBulkCopy
标签:定义 数据库 cti 测试 导致 需要 creat blog str