|
1 | 1 | using System; |
2 | 2 | using System.Collections.Generic; |
3 | 3 | using System.Linq; |
| 4 | +using System.Reflection; |
4 | 5 |
|
5 | 6 | namespace SqlKata |
6 | 7 | { |
@@ -343,5 +344,48 @@ public object FindVariable(string variable) |
343 | 344 | throw new Exception($"Variable '{variable}' not found"); |
344 | 345 | } |
345 | 346 |
|
| 347 | + /// <summary> |
| 348 | + /// Build a dictionary from plain object, intended to be used with Insert and Update queries |
| 349 | + /// </summary> |
| 350 | + /// <param name="data">the plain C# object</param> |
| 351 | + /// <param name="considerKeys"> |
| 352 | + /// When true it will search for properties with the [Key] attribute |
| 353 | + /// and add it automatically to the Where clause |
| 354 | + /// </param> |
| 355 | + /// <returns></returns> |
| 356 | + private Dictionary<string, object> BuildDictionaryFromObject(object data, bool considerKeys = false) |
| 357 | + { |
| 358 | + |
| 359 | + var dictionary = new Dictionary<string, object>(); |
| 360 | + var props = data.GetType().GetRuntimeProperties(); |
| 361 | + |
| 362 | + foreach (var property in props) |
| 363 | + { |
| 364 | + if (property.GetCustomAttribute(typeof(IgnoreAttribute)) != null) |
| 365 | + { |
| 366 | + continue; |
| 367 | + } |
| 368 | + |
| 369 | + var value = property.GetValue(data); |
| 370 | + |
| 371 | + var colAttr = property.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute; |
| 372 | + |
| 373 | + var name = colAttr?.Name ?? property.Name; |
| 374 | + |
| 375 | + dictionary.Add(name, value); |
| 376 | + |
| 377 | + if (considerKeys && colAttr != null) |
| 378 | + { |
| 379 | + if ((colAttr as KeyAttribute) != null) |
| 380 | + { |
| 381 | + this.Where(name, value); |
| 382 | + } |
| 383 | + } |
| 384 | + |
| 385 | + } |
| 386 | + |
| 387 | + return dictionary; |
| 388 | + } |
| 389 | + |
346 | 390 | } |
347 | 391 | } |
0 commit comments