/// <summary>
2 /// SqlSugar 注入Service的扩展方法
3 /// </summary>
4 public static class SqlSugarServiceCollectionExtensions
5 {
6 /// <summary>
7 /// SqlSugar上下文注入
8 /// </summary>
9 /// <typeparam name="TSugarContext">要注册的上下文的类型</typeparam>
10 /// <param name="serviceCollection"></param>
11 /// <param name="configAction"></param>
12 /// <param name="lifetime">用于在容器中注册TSugarClient服务的生命周期</param>
13 /// <returns></returns>
14 public static IServiceCollection AddSqlSugarClient<TSugarContext>(
this IServiceCollection serviceCollection, Action<IServiceProvider, ConnectionConfig> configAction, ServiceLifetime lifetime =
ServiceLifetime.Singleton)
15 where TSugarContext : IDbFactory
16 {
17 serviceCollection.AddMemoryCache().AddLogging();
18 serviceCollection.TryAdd(
new ServiceDescriptor(
typeof(ConnectionConfig), p =>
ConnectionConfigFactory(p, configAction), lifetime));
19 serviceCollection.Add(
new ServiceDescriptor(
typeof(ConnectionConfig), p =>
ConnectionConfigFactory(p, configAction), lifetime));
20 serviceCollection.TryAdd(
new ServiceDescriptor(
typeof(TSugarContext),
typeof(TSugarContext), lifetime));
21 return serviceCollection;
22 }
23
24 private static ConnectionConfig ConnectionConfigFactory(IServiceProvider applicationServiceProvider, Action<IServiceProvider, ConnectionConfig>
configAction)
25 {
26 var config =
new ConnectionConfig();
27 configAction.Invoke(applicationServiceProvider, config);
28 return config;
29 }
30 }
注入扩展

1 public interface IDbFactory
2 {
3 SqlSugarClient GetDbContext(Action<Exception> onErrorEvent);
4 SqlSugarClient GetDbContext(Action<string, SugarParameter[]> onExecutedEvent);
5 SqlSugarClient GetDbContext(Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> onExecutingChangeSqlEvent);
6 SqlSugarClient GetDbContext(Action<string, SugarParameter[]> onExecutedEvent = null, Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> onExecutingChangeSqlEvent = null, Action<Exception> onErrorEvent = null);
7 }
IDbFactory

1 public class DbFactory : IDbFactory
2 {
3 private readonly ILogger _logger;
4 private readonly ConnectionConfig _config;
5
6 public DbFactory(ConnectionConfig config, ILogger<DbFactory> logger)
7 {
8 this._logger = logger;
9 this._config = config;
10 }
11
12 public SqlSugarClient GetDbContext(Action<Exception> onErrorEvent) => GetDbContext(null, null, onErrorEvent);
13 public SqlSugarClient GetDbContext(Action<string, SugarParameter[]> onExecutedEvent) => GetDbContext(onExecutedEvent);
14 public SqlSugarClient GetDbContext(Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> onExecutingChangeSqlEvent) => GetDbContext(null, onExecutingChangeSqlEvent);
15 public SqlSugarClient GetDbContext(Action<string, SugarParameter[]> onExecutedEvent = null, Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> onExecutingChangeSqlEvent = null, Action<Exception> onErrorEvent = null)
16 {
17 SqlSugarClient db = new SqlSugarClient(_config)
18 {
19 Aop =
20 {
21 OnExecutingChangeSql = onExecutingChangeSqlEvent,
22 OnError = onErrorEvent ?? ((Exception ex) => { this._logger.LogError(ex, "ExecuteSql Error"); }),
23 OnLogExecuted =onExecutedEvent?? ((string sql, SugarParameter[] pars) =>
24 {
25 var keyDic = new KeyValuePair<string, SugarParameter[]>(sql, pars);
26 this._logger.LogInformation($"ExecuteSql:【{keyDic.ToJson()}】");
27 })
28 }
29 };
30 return db;
31 }
32 }
DbFactory

public interface IRepository
{
}
IRepository

1 public class Repository<TFactory, TIRepository> : IRepository where TFactory : IDbFactory where TIRepository : IRepository
2 {
3 protected readonly ILogger Log;
4 protected readonly TFactory Factory;
5 protected readonly TIRepository DbRepository;
6 protected SqlSugarClient DbContext => this.Factory.GetDbContext();
7
8 public Repository(TFactory factory) => Factory = factory;
9 public Repository(TFactory factory, ILogger logger) : this(factory) => Log = logger;
10 public Repository(TFactory factory, TIRepository repository) : this(factory) => DbRepository = repository;
11 public Repository(TFactory factory, TIRepository repository, ILogger logger) : this(factory, repository) => Log = logger;
12 }
13
14 public class Repository<TFactory> : IRepository where TFactory : IDbFactory
15 {
16 protected readonly ILogger Log;
17 protected readonly TFactory Factory;
18 protected SqlSugarClient DbContext => this.Factory.GetDbContext();
19
20 public Repository(TFactory factory) => Factory = factory;
21 public Repository(TFactory factory, ILogger logger) : this(factory) => Log = logger;
22 }
Repository

1 public static class SugarFactoryExtensions
2 {
3
4 #region 根据主键获取实体对象
5
6 /// <summary>
7 /// 根据主键获取实体对象
8 /// </summary>
9 /// <typeparam name="TSource">数据源类型</typeparam>
10 /// <param name="db"></param>
11 /// <param name="id"></param>
12 /// <returns></returns>
13 public static TSource GetById<TSource>(this SqlSugarClient db, dynamic id) where TSource : EntityBase, new()
14 {
15 return db.Queryable<TSource>().InSingle(id);
16 }
17
18 /// <summary>
19 /// 根据主键获取实体对象
20 /// </summary>
21 /// <typeparam name="TSource">数据源类型</typeparam>
22 /// <typeparam name="TMap">数据源映射类型</typeparam>
23 /// <param name="db"></param>
24 /// <param name="id"></param>
25 /// <returns></returns>
26 public static TMap GetById<TSource, TMap>(this SqlSugarClient db, dynamic id) where TSource : EntityBase, new()
27 {
28 TSource model = db.Queryable<TSource>().InSingle(id);
29 return model.Map<TSource, TMap>();
30 }
31
32 #endregion
33
34 #region 根据Linq表达式条件获取单个实体对象
35
36 /// <summary>
37 /// 根据条件获取单个实体对象
38 /// </summary>
39 /// <typeparam name="TSource">数据源类型</typeparam>
40 /// <param name="db"></param>
41 /// <param name="whereExp"></param>
42 /// <returns></returns>
43 public static TSource Get<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
44 {
45 return db.Queryable<TSource>().Where(whereExp).Single();
46 }
47
48 /// <summary>
49 /// 根据条件获取单个实体对象
50 /// </summary>
51 /// <typeparam name="TSource">数据源类型</typeparam>
52 /// <typeparam name="TMap">数据源映射类型</typeparam>
53 /// <param name="db"></param>
54 /// <param name="whereExp">条件表达式</param>
55 /// <returns></returns>
56 public static TMap Get<TSource, TMap>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
57 {
58 TSource model = db.Queryable<TSource>().Where(whereExp).Single();
59 return model.Map<TSource, TMap>();
60 }
61
62 #endregion
63
64 #region 获取所有实体列表
65
66 /// <summary>
67 /// 获取所有实体列表
68 /// </summary>
69 /// <typeparam name="TSource">数据源类型</typeparam>
70 /// <param name="db"></param>
71 /// <returns></returns>
72 public static List<TSource> GetList<TSource>(this SqlSugarClient db) where TSource : EntityBase, new()
73 {
74 return db.Queryable<TSource>().ToList();
75 }
76
77 /// <summary>
78 /// 获取实体列表
79 /// </summary>
80 /// <typeparam name="TSource">数据源类型</typeparam>
81 /// <typeparam name="TMap">数据源映射类型</typeparam>
82 /// <param name="db"></param>
83 /// <returns></returns>
84 public static List<TMap> GetList<TSource, TMap>(this SqlSugarClient db) where TSource : EntityBase, new()
85 {
86 var result = db.Queryable<TSource>().ToList();
87 return result.Map<List<TSource>, List<TMap>>();
88 }
89
90 #endregion
91
92 #region 根据Linq表达式条件获取列表
93
94 /// <summary>
95 /// 根据条件获取实体列表
96 /// </summary>
97 /// <typeparam name="TSource">数据源类型</typeparam>
98 /// <param name="db"></param>
99 /// <param name="whereExp">条件表达式</param>
100 /// <returns></returns>
101 public static List<TSource> GetList<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
102 {
103 return db.Queryable<TSource>().Where(whereExp).ToList();
104 }
105
106 /// <summary>
107 /// 根据条件获取实体列表
108 /// </summary>
109 /// <typeparam name="TSource">数据源类型</typeparam>
110 /// <typeparam name="TMap">数据源映射类型</typeparam>
111 /// <param name="db"></param>
112 /// <param name="whereExp">条件表达式</param>
113 /// <returns></returns>
114 public static List<TMap> GetList<TSource, TMap>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
115 {
116 var result = db.Queryable<TSource>().Where(whereExp).ToList();
117 return result.Map<List<TSource>, List<TMap>>();
118 }
119
120 #endregion
121
122 #region 根据Sugar条件获取列表
123
124 /// <summary>
125 /// 根据条件获取实体列表
126 /// </summary>
127 /// <typeparam name="TSource"></typeparam>
128 /// <param name="db"></param>
129 /// <param name="conditionals">Sugar调价表达式集合</param>
130 /// <returns></returns>
131 public static List<TSource> GetList<TSource>(this SqlSugarClient db, List<IConditionalModel> conditionals) where TSource : EntityBase, new()
132 {
133 return db.Queryable<TSource>().Where(conditionals).ToList();
134 }
135
136 /// <summary>
137 /// 根据条件获取实体列表
138 /// </summary>
139 /// <typeparam name="TSource">数据源类型</typeparam>
140 /// <typeparam name="TMap">数据源映射类型</typeparam>
141 /// <param name="db"></param>
142 /// <param name="conditionals">Sugar调价表达式集合</param>
143 /// <returns></returns>
144 public static List<TMap> GetList<TSource, TMap>(this SqlSugarClient db, List<IConditionalModel> conditionals) where TSource : EntityBase, new()
145 {
146 var result = db.Queryable<TSource>().Where(conditionals).ToList();
147 return result.Map<List<TSource>, List<TMap>>();
148 }
149
150 #endregion
151
152 #region 是否包含某个元素
153 /// <summary>
154 /// 是否包含某个元素
155 /// </summary>
156 /// <typeparam name="TSource"></typeparam>
157 /// <param name="db"></param>
158 /// <param name="whereExp">条件表达式</param>
159 /// <returns></returns>
160 public static bool Exist<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
161 {
162 return db.Queryable<TSource>().Where(whereExp).Any();
163 }
164 #endregion
165
166 #region 新增实体对象
167 /// <summary>
168 /// 新增实体对象
169 /// </summary>
170 /// <typeparam name="TSource"></typeparam>
171 /// <param name="db"></param>
172 /// <param name="insertObj"></param>
173 /// <returns></returns>
174 public static bool Insert<TSource>(this SqlSugarClient db, TSource insertObj) where TSource : EntityBase, new()
175 {
176 return db.Insertable(insertObj).ExecuteCommand() > 0;
177 }
178
179 /// <summary>
180 /// 新增实体对象
181 /// </summary>
182 /// <typeparam name="TSource"></typeparam>
183 /// <typeparam name="TMap"></typeparam>
184 /// <param name="db"></param>
185 /// <param name="insertDto"></param>
186 /// <returns></returns>
187 public static bool Insert<TSource, TMap>(this SqlSugarClient db, TSource insertDto) where TMap : EntityBase, new()
188 {
189 var entity = insertDto.Map<TSource, TMap>();
190 return db.Insertable(entity).ExecuteCommand() > 0;
191 }
192 #endregion
193
194 #region 批量新增实体对象
195 /// <summary>
196 /// 批量新增实体对象
197 /// </summary>
198 /// <typeparam name="TSource"></typeparam>
199 /// <param name="db"></param>
200 /// <param name="insertObjs"></param>
201 /// <returns></returns>
202 public static bool InsertRange<TSource>(this SqlSugarClient db, List<TSource> insertObjs) where TSource : EntityBase, new()
203 {
204 return db.Insertable(insertObjs).ExecuteCommand() > 0;
205 }
206
207 /// <summary>
208 /// 批量新增实体对象
209 /// </summary>
210 /// <typeparam name="TSource"></typeparam>
211 /// <typeparam name="TMap"></typeparam>
212 /// <param name="db"></param>
213 /// <param name="insertObjs"></param>
214 /// <returns></returns>
215 public static bool InsertRange<TSource, TMap>(this SqlSugarClient db, List<TSource> insertObjs) where TMap : EntityBase, new()
216 {
217 var entitys = insertObjs.Map<List<TSource>, List<TMap>>();
218 return db.Insertable(entitys).ExecuteCommand() > 0;
219 }
220 #endregion
221
222 #region 更新单个实体对象
223 /// <summary>
224 /// 更新单个实体对象
225 /// </summary>
226 /// <typeparam name="TSource"></typeparam>
227 /// <param name="db"></param>
228 /// <param name="updateObj"></param>
229 /// <returns></returns>
230 public static bool Update<TSource>(this SqlSugarClient db, TSource updateObj) where TSource : EntityBase, new()
231 {
232 return db.Updateable(updateObj).ExecuteCommand() > 0;
233 }
234 #endregion
235
236 #region 根据条件批量更新实体指定列
237 /// <summary>
238 /// 根据条件批量更新实体指定列
239 /// </summary>
240 /// <typeparam name="TSource"></typeparam>
241 /// <param name="db"></param>
242 /// <param name="columns">需要更新的列</param>
243 /// <param name="whereExp">条件表达式</param>
244 /// <returns></returns>
245 public static bool Update<TSource>(this SqlSugarClient db, Expression<Func<TSource, TSource>> columns, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
246 {
247 return db.Updateable<TSource>().UpdateColumns(columns).Where(whereExp).ExecuteCommand() > 0;
248 }
249 #endregion
250
251 #region 物理删除实体对象
252
253 /// <summary>
254 /// 物理删除实体对象
255 /// </summary>
256 /// <typeparam name="TSource"></typeparam>
257 /// <param name="db"></param>
258 /// <param name="deleteObj"></param>
259 /// <returns></returns>
260 public static bool Delete<TSource>(this SqlSugarClient db, TSource deleteObj) where TSource : EntityBase, new()
261 {
262 return db.Deleteable<TSource>().Where(deleteObj).ExecuteCommand() > 0;
263 }
264
265 /// <summary>
266 /// 物理删除实体对象
267 /// </summary>
268 /// <typeparam name="TSource"></typeparam>
269 /// <param name="db"></param>
270 /// <param name="whereExp">条件表达式</param>
271 /// <returns></returns>
272 public static bool Delete<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
273 {
274 return db.Deleteable<TSource>().Where(whereExp).ExecuteCommand() > 0;
275 }
276
277 /// <summary>
278 /// 根据主键物理删除实体对象
279 /// </summary>
280 /// <typeparam name="TSource"></typeparam>
281 /// <param name="db"></param>
282 /// <param name="id"></param>
283 /// <returns></returns>
284 public static bool DeleteById<TSource>(this SqlSugarClient db, dynamic id) where TSource : EntityBase, new()
285 {
286 return db.Deleteable<TSource>().In(id).ExecuteCommand() > 0;
287 }
288
289 /// <summary>
290 /// 根据主键批量物理删除实体集合
291 /// </summary>
292 /// <typeparam name="TSource"></typeparam>
293 /// <param name="db"></param>
294 /// <param name="ids"></param>