From 1c8ea86fd31bb01b84b2fd50f86bbe57a9e3aedf Mon Sep 17 00:00:00 2001 From: xRain Date: Sat, 5 Jun 2021 11:20:32 +0800 Subject: [PATCH] add basemodel --- Models/SimApiBaseModel.cs | 45 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Models/SimApiBaseModel.cs diff --git a/Models/SimApiBaseModel.cs b/Models/SimApiBaseModel.cs new file mode 100644 index 0000000..5223348 --- /dev/null +++ b/Models/SimApiBaseModel.cs @@ -0,0 +1,45 @@ +using System; +using System.Linq; +using System.Text.Json; + +namespace SimApi.Models +{ + public class SimApiBaseModel + { + protected virtual string[] MapperIgnoreField { get; set; } = {"Id", "CreatedAt", "UpdatedAt"}; + protected virtual string UpdatedTimeField { get; set; } = "UpdatedAt"; + + public void MapData(TS source, bool mapAll = false) + { + //获取要赋值的源数据不为null的项目 + var sourceProps = source.GetType().GetProperties().Where(x => x.GetValue(source) != null) + .Select(x => new {x.Name, x.PropertyType}) + .ToDictionary(x => x.Name, x => x.PropertyType); + + //获取目标对象的属性信息 + var targetProps = GetType().GetProperties().Select(x => new {x.Name, x.PropertyType}) + .ToDictionary(x => x.Name, x => x.PropertyType); + foreach (var sp in sourceProps) + { + //检查源对象不为空的属性是否在目标对象中存在 + if (targetProps.ContainsKey(sp.Key) && sp.Value == targetProps[sp.Key] && + (!MapperIgnoreField.Contains(sp.Key) || mapAll)) + { + GetType().GetProperty(sp.Key)? + .SetValue(this, source.GetType().GetProperty(sp.Key)?.GetValue(source)); + } + } + + UpdateTime(); + } + + /// + /// 更新update时间 + /// + /// + public void UpdateTime() + { + GetType().GetProperty(UpdatedTimeField)?.SetValue(this, DateTime.Now); + } + } +} \ No newline at end of file