gpt4 book ai didi

c# - 基于 AutoMapper 约定的系统

转载 作者:行者123 更新时间:2023-11-30 22:42:05 25 4
gpt4 key购买 nike

我正在尝试将我的 ViewModel 类映射到 Web 服务 DTO 对象。 ViewModels 使用以下约定:

CustomerViewModel 
OrderStatusViewModel

WCF 类 DTO 具有以下约定:

Customer
OrderStatus

此外,如果 WCF 类 DTO 具有以下约定怎么办:

CustomerDTO 
OrderStatusDTO

问题是如何使用 AutoMapper 在 ViewModel 和 WCF 类之间进行映射?由于上述配置,我想以某种方式映射所有 future 的 ViewModel 和 WCF 类自动映射。

最佳答案

我之前写过这个。如果您愿意,请查看:http://www.weirdlover.com/2010/07/01/the-big-boy-mvc-series-part-22-whoop/

添加对Automapper的引用

创建一个基 ViewModel 类:

public abstract class MappedTo<T>
{
public MappedTo()
{
Mapper.CreateMap(GetType(), typeof(T));
}

public T Convert()
{
return (T)Mapper.Map(this, this.GetType(), typeof(T));
}
}

创建一个 ViewModel 类,它继承上述基类。指定您想将 ViewModel 映射到哪个 DTO:

class AddressViewModel : MappedTo<Address>
{
public string Line1 { get; set; }
public string City { get; set; }
public string State { get; set; }
}

AutoMapper 应该处理其余的:

static void Main(string[] args)
{
AddressViewModel addressVm = new AddressViewModel
{
Line1 = "555 Honolulu Street",
City = "Honolulu",
State = "HI"
};

Address address = addressVm.Convert();

Console.WriteLine(address.Line1);
Console.WriteLine(address.City);
Console.WriteLine(address.State);
Console.ReadLine();
}

如果你想变得更有趣,你可以创建另一个 ViewModel 基础类,它允许你传入你自己的 TypeConverter:

public abstract class MappedTo<T, TConverter>
{
public MappedTo()
{
Mapper.CreateMap(GetType(), typeof(T)).ConvertUsing(typeof(TConverter));
}

public T Convert()
{
return (T)Mapper.Map(this, this.GetType(), typeof(T));
}
}

然后,您可以根据需要从 ViewModel 转换为 DTO:

public class AddressConverter : TypeConverter<AddressViewModel, Address>
{
protected override Address ConvertCore(AddressViewModel source)
{
return new Address
{
Line1 = source.Line1 + " foo",
City = source.City + " foo",
State = source.State + " foo"
};
}
}

关于c# - 基于 AutoMapper 约定的系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4609016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com