我後來寫了關於這個。檢查「,如果你想呃了:http://www.weirdlover.com/2010/07/01/the-big-boy-mvc-series-part-22-whoop/
增加提及Automapper
創建基礎視圖模型類:
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類,從繼承上述基地。指定您希望您的視圖模型映射到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();
}
如果你想獲得幻想,您可以創建另一個視圖模型的基礎CALSS,可以讓你在自己的的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));
}
}
然後,您可以從您的視圖模型轉換成你的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"
};
}
}
也許這只是我,但我實在不明白一個問題在這裏。我看到你對你的命名約定作了一些陳述,但是它是什麼問題呢? – spinon 2011-01-05 20:50:03
查看更新的問題! – johndoe 2011-01-05 20:51:33