(精华)2020年7月3日 ASP.NET Core AutoMapper实现类的相互映射(工具版)

需要安装如下包

AutoMapper
public void ConfigureServices(IServiceCollection services)
{
    #region 自动映射拥有MapAttribute的类
    services.AddAutoMapper();
    #endregion
}
/// <summary>
/// 使用AutoMapper自动映射拥有MapAttribute的类
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="configure">自定义配置</param>
public static IServiceCollection AddAutoMapper(this IServiceCollection services, Action<IMapperConfigurationExpression> configure = null)
{
    List<(Type from, Type[] targets)> maps = new List<(Type from, Type[] targets)>();

    maps.AddRange(GlobalData.AllFxTypes.Where(x => x.GetCustomAttribute<MapAttribute>() != null)
        .Select(x => (x, x.GetCustomAttribute<MapAttribute>().TargetTypes)));

    var configuration = new MapperConfiguration(cfg =>
    {
        maps.ForEach(aMap =>
        {
            aMap.targets.ToList().ForEach(aTarget =>
            {
                cfg.CreateMap(aMap.from, aTarget).IgnoreAllNonExisting(aMap.from, aTarget).ReverseMap();
            });
        });

        cfg.AddMaps(GlobalData.AllFxAssemblies);

        //自定义映射
        configure?.Invoke(cfg);
    });

#if DEBUG
    //只在Debug时检查配置
    configuration.AssertConfigurationIsValid();
#endif
    services.AddSingleton(configuration.CreateMapper());

    return services;
}
[Map(typeof(Base_User))]
public class Base_UserDTO : Base_User
{
    public string RoleNames { get => string.Join(",", RoleNameList ?? new List<string>()); }
    public List<string> RoleIdList { get; set; }
    public List<string> RoleNameList { get; set; }
    public RoleTypes RoleType
    {
        get
        {
            int type = 0;

            var values = typeof(RoleTypes).GetEnumValues();
            foreach (var aValue in values)
            {
                if (RoleNames.Contains(aValue.ToString()))
                    type += (int)aValue;
            }

            return (RoleTypes)type;
        }
    }
    public string DepartmentName { get; set; }
    public string SexText { get => Sex.GetDescription(); }
    public string BirthdayText { get => Birthday?.ToString("yyyy-MM-dd"); }
}
/// <summary>
/// 系统用户表
/// </summary>
[Table("Base_User")]
public class Base_User
{

    /// <summary>
    /// 主键
    /// </summary>
    [Key, Column(Order = 1)]
    public String Id { get; set; }

    /// <summary>
    /// 创建时间
    /// </summary>
    public DateTime CreateTime { get; set; }

    /// <summary>
    /// 创建人Id
    /// </summary>
    public String CreatorId { get; set; }

    /// <summary>
    /// 否已删除
    /// </summary>
    public Boolean Deleted { get; set; }

    /// <summary>
    /// 用户名
    /// </summary>
    public String UserName { get; set; }

    /// <summary>
    /// 密码
    /// </summary>
    public String Password { get; set; }

    /// <summary>
    /// 姓名
    /// </summary>
    public String RealName { get; set; }

    /// <summary>
    /// 性别
    /// </summary>
    public Sex Sex { get; set; }

    /// <summary>
    /// 出生日期
    /// </summary>
    public DateTime? Birthday { get; set; }

    /// <summary>
    /// 所属部门Id
    /// </summary>
    public String DepartmentId { get; set; }
}

public enum Sex
{
    [Description("男人")]
    Man = 1,

    [Description("女人")]
    Woman = 0
}
public class MapAttribute : Attribute
{
    public MapAttribute(params Type[] targetTypes)
    {
        TargetTypes = targetTypes;
    }
    public Type[] TargetTypes { get; }
}

具体的其他相关类请移到类库中去查找本人博客都有

©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页