我有CustomerDto
和CustomerDomainModel
。我希望 Automapper在构造对象时使用DataBindingFactory
这里提到的。CustomerDomainModel
我在课堂上看过ConstructUsing
和AfterMap
函数,Mapper
但我找不到完成我想做的事情的方法。我该怎么做呢?
问问题
2205 次
1 回答
3
您应该可以使用ConstructUsing
它。不过,您可能必须像这样显式转换为正确的表达式:
class Program
{
private static void Main(string[] args)
{
Mapper.CreateMap<CustomerDto, CustomerDomainModel>()
.ForMember(d => d.Id, opt => opt.Ignore())
.ConstructUsing((Func<ResolutionContext, CustomerDomainModel>) (rc => DataBindingFactory.Create<CustomerDomainModel>()));
var dto = new CustomerDto {FirstName = "First", LastName = "Last"};
var domain = Mapper.Map<CustomerDto, CustomerDomainModel>(dto);
Console.WriteLine("First: " + domain.FirstName);
Console.WriteLine("Last: " + domain.LastName);
Console.ReadLine();
}
}
public class CustomerDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class CustomerDomainModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public static class DataBindingFactory
{
public static T Create<T>()
{
return Activator.CreateInstance<T>();
}
}
于 2013-02-23T16:07:42.800 回答