From b1574678756c04677859061ef2cd676233246f3f Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 13 Dec 2022 11:14:30 +0800 Subject: Develop secret api. v33 --- .../CrupestApi.Commons/Crud/EntityJsonHelper.cs | 38 ++++++++++++++++++++++ 1 file changed, 38 insertions(+) (limited to 'docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/EntityJsonHelper.cs') 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 where TEntity : class var dictionary = ConvertEntityToDictionary(entity); return JsonSerializer.Serialize(dictionary, _jsonSerializerOptions); } + + public virtual TEntity ConvertDictionaryToEntityForInsert(IReadOnlyDictionary dictionary) + { + var result = Activator.CreateInstance()!; + + 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; + } } -- cgit v1.2.3