You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
2.1 KiB
C#

7 months ago
using Mapster;
using System;
namespace SlnMesnac.WPF.Library
{
public class CoreMapper
{
/// <summary>
/// Map source object to destination object
/// </summary>
/// <typeparam name="TDestination"> The type of the destination. </typeparam>
/// <param name="source"> The source object. </param>
/// <returns>The destination object. </returns>
/// <exception cref="ArgumentNullException"> Thrown when source is null. </exception>
public static TDestination Map<TDestination>(object source)
{
if (source == null)
throw new ArgumentNullException("Map Error : source is null");
TypeAdapterConfig config = new TypeAdapterConfig();
config.NewConfig<string, Guid>().MapWith(dest => string.IsNullOrEmpty(dest.Trim()) ? Guid.Empty : new Guid(dest));
config.NewConfig<string, Guid?>().MapWith(dest => string.IsNullOrEmpty(dest.Trim()) ? null : new Guid(dest));
config.NewConfig<Guid, string>().MapWith(dest => dest.ToString());
config.NewConfig<string, DateTime>().MapWith(dest => string.IsNullOrEmpty(dest) ? DateTime.Now : Convert.ToDateTime(dest));
config.NewConfig<string, DateTime?>().MapWith(dest => string.IsNullOrEmpty(dest) ? null : Convert.ToDateTime(dest));
config.NewConfig<DateTime, string>().MapWith(dest => dest.ToString());
// var c = source.Adapt(destination, config2);
config.NewConfig<string, string>().MapWith(dest => dest.Trim());
// config.ForType<string, Guid>().Map(member: guid => guid, source: @string => string.IsNullOrEmpty(@string) ? Guid.Empty : new Guid(@string));
// config.ForType<Guid, String>().Map(member: @string => @string, source: guid => ("wode"));
config.Default.IgnoreNullValues(true);//忽略null原本的类字段的值是null映射出来是"",int? null
config.Default.NameMatchingStrategy(NameMatchingStrategy.IgnoreCase);//忽略大小写
var destination = source.Adapt<TDestination>(config);
return destination;
}
}
}