Files
simapi-net/Models/SimApiBaseModel.cs
T

89 lines
2.8 KiB
C#
Raw Normal View History

2021-06-05 11:20:32 +08:00
using System;
2024-03-23 07:10:17 +08:00
using System.ComponentModel.DataAnnotations.Schema;
2021-06-05 11:20:32 +08:00
using System.Linq;
using SimApi.Helpers;
2021-06-05 11:20:32 +08:00
2024-03-23 07:29:43 +08:00
namespace SimApi.Models;
public class SimApiBaseModel
2021-06-05 11:20:32 +08:00
{
2024-03-23 07:29:43 +08:00
[Column(Order = 1)]
public string Id { get; set; } = Guid.NewGuid().ToString();
[Column(Order = 9998)]
public DateTime UpdatedAt { get; set; } = SimApiUtil.CstNow;
[Column(Order = 9999)]
public DateTime CreatedAt { get; set; } = SimApiUtil.CstNow;
protected virtual string[] MapperIgnoreField { get; set; } = { "Id", "CreatedAt", "UpdatedAt" };
protected virtual string UpdatedTimeField { get; set; } = "UpdatedAt";
public void MapData<TS>(TS source, bool mapAll = false)
2021-06-05 11:20:32 +08:00
{
2024-03-23 07:29:43 +08:00
//获取要赋值的源数据不为null的项目
var sourceProps = source.GetType().GetProperties().Where(x => x.GetValue(source) != null)
.Select(x => new
2021-06-05 11:20:32 +08:00
{
2024-03-23 07:29:43 +08:00
x.Name,
x.PropertyType
})
.ToDictionary(x => x.Name, x => x.PropertyType);
2021-06-05 11:20:32 +08:00
2024-03-23 07:29:43 +08:00
//获取目标对象的属性信息
var targetProps = GetType().GetProperties().Select(x => new
2021-06-08 10:54:51 +08:00
{
2024-03-23 07:29:43 +08:00
x.Name,
x.PropertyType
})
.ToDictionary(x => x.Name, x => x.PropertyType);
foreach (var sp in sourceProps.Where(sp =>
targetProps.ContainsKey(sp.Key) && sp.Value == targetProps[sp.Key] &&
(!MapperIgnoreField.Contains(sp.Key) || mapAll)))
2021-06-05 11:20:32 +08:00
{
2024-03-23 07:29:43 +08:00
GetType().GetProperty(sp.Key)?
.SetValue(this, source.GetType().GetProperty(sp.Key)?.GetValue(source));
2021-06-05 11:20:32 +08:00
}
2024-03-23 07:29:43 +08:00
UpdateTime();
}
public void MapData<TS>(TS source, string[] mapFields)
{
//获取要赋值的源数据不为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.Where(sp =>
targetProps.ContainsKey(sp.Key) && sp.Value == targetProps[sp.Key] &&
mapFields.Contains(sp.Key)))
{
GetType().GetProperty(sp.Key)?
.SetValue(this, source.GetType().GetProperty(sp.Key)?.GetValue(source));
}
UpdateTime();
}
/// <summary>
/// 更新update时间
/// </summary>
/// <returns></returns>
public void UpdateTime()
{
GetType().GetProperty(UpdatedTimeField)?.SetValue(this, SimApiUtil.CstNow);
2021-06-05 11:20:32 +08:00
}
}