aboutsummaryrefslogtreecommitdiff
path: root/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/EntityJsonHelper.cs
diff options
context:
space:
mode:
Diffstat (limited to 'docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/EntityJsonHelper.cs')
-rw-r--r--docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/EntityJsonHelper.cs38
1 files changed, 38 insertions, 0 deletions
diff --git a/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/EntityJsonHelper.cs b/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/EntityJsonHelper.cs
index 19208d8..bbbbb4c 100644
--- a/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/EntityJsonHelper.cs
+++ b/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/EntityJsonHelper.cs
@@ -53,4 +53,42 @@ public class EntityJsonHelper<TEntity> where TEntity : class
var dictionary = ConvertEntityToDictionary(entity);
return JsonSerializer.Serialize(dictionary, _jsonSerializerOptions);
}
+
+ public virtual TEntity ConvertDictionaryToEntityForInsert(IReadOnlyDictionary<string, object?> dictionary)
+ {
+ var result = Activator.CreateInstance<TEntity>()!;
+
+ foreach (var column in _table.PropertyColumns)
+ {
+ var propertyInfo = column.PropertyInfo!;
+ var value = dictionary.GetValueOrDefault(column.ColumnName);
+ if (column.IsGenerated)
+ {
+ if (value is not null)
+ {
+ throw new UserException($"{propertyInfo.Name} is auto generated. Don't specify it.");
+ }
+ }
+
+ if (value is null)
+ {
+ if (column.IsNotNull && !column.CanBeGenerated)
+ {
+ throw new UserException($"{propertyInfo.Name} can't be null.");
+ }
+ propertyInfo.SetValue(result, null);
+ }
+ else
+ {
+ // Check type
+ var columnType = column.ColumnType;
+ if (columnType.ClrType.IsAssignableFrom(value.GetType()))
+ propertyInfo.SetValue(result, value);
+ else
+ throw new UserException($"{propertyInfo.Name} is of wrong type.");
+ }
+ }
+
+ return result;
+ }
}