-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlServerRepository.cs
More file actions
93 lines (82 loc) · 2.73 KB
/
Copy pathSqlServerRepository.cs
File metadata and controls
93 lines (82 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using Common;
using Common.DB;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
namespace Repository
{
public class SqlServerRepository : DbRepository, IRepository
{
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
public SqlServerRepository()
: base(null, DatabaseType.SqlServer, null)
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="conStr">数据库连接名</param>
public SqlServerRepository(string conStr)
: base(conStr, DatabaseType.SqlServer, null)
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="conStr">数据库连接名</param>
/// <param name="entityNamespace">实体命名空间</param>
public SqlServerRepository(string conStr, string entityNamespace)
: base(conStr, DatabaseType.SqlServer, entityNamespace)
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="dbContext">数据库连接上下文</param>
public SqlServerRepository(DbContext dbContext)
: base(dbContext, DatabaseType.SqlServer, null)
{
}
#endregion
#region 插入数据
/// <summary>
/// 使用Bulk批量插入数据(适合大数据量,速度非常快)
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entities">数据</param>
public override void BulkInsert<T>(List<T> entities)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = _connectionString;
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
string tableName = string.Empty;
var tableAttribute = typeof(T).GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault();
if (tableAttribute != null)
tableName = ((TableAttribute)tableAttribute).Name;
else
tableName = typeof(T).Name;
SqlBulkCopy sqlBC = new SqlBulkCopy(conn)
{
BatchSize = 100000,
BulkCopyTimeout = 0,
DestinationTableName = tableName
};
using (sqlBC)
{
sqlBC.WriteToServer(entities.ToDataTable());
}
}
}
#endregion
}
}