(精華)2020年7月3日 ASP.NET Core AutoMapper實現類的相互對映(工具版)

愚公搬程式碼發表於2020-07-03

需要安裝如下包

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; }
}

具體的其他相關類請移到類庫中去查詢本人部落格都有

相關文章