我想將AutoMapper整合到我的項目中,現在我知道如何project EntityFramework objects,但我總是收到這個異常:無法從System.Byte創建映射表達式到System.Int32。所以,我想我會成爲一個自定義類型轉換,它會工作,但它並不:AutoMapper自定義TypeConverter不能正常工作
public sealed class ByteToInt32Converter : TypeConverter<byte, int> {
protected override int ConvertCore(
byte source) {
return (int)source;
}
}
Mapper.CreateMap<byte, int>().ConvertUsing<ByteToInt32Converter>();
綜觀文檔和其他搜索結果,這應該是正確的,但我仍然得到一個例外。做什麼?
更新
每斯科特的要求,這是我的源對象,Company
,而目標對象SelectItem
:
public partial class Company {
public byte Id { get; set; }
public string Name { get; set; }
#region Relationship Properties
public byte? ParentCompanyId { get; set; }
public virtual ICollection<Company> Companies { get; private set; }
public virtual ICollection<Employee> Employees { get; private set; }
public virtual Company ParentCompany { get; set; }
public virtual ICollection<State> States { get; private set; }
#endregion
public Company() {
this.Companies = new List<Company>();
this.Employees = new List<Employee>();
this.States = new List<State>();
}
}
public sealed class SelectItem : ISelectItem {
public string Key { get; set; }
public int Value { get; set; }
}
public interface ISelectItem : IItem {
string Key { get; set; }
int Value { get; set; }
}
public interface IItem {
}
而這裏的映射代碼:
Mapper.CreateMap<Company, SelectItem>()
.ForMember(
d => d.Key,
o => o.MapFrom(
s => s.Name))
.ForMember(
d => d.Value,
o => o.MapFrom(
s => s.Id));
我m基本上試圖將Company
對象扁平化爲「鍵值pa ir「的對象,我可以將其傳入MVC Html.DropDownList()
。我並不特別在意匹配Key Id的類型,因爲我只是使用它來生成下拉列表,所以我只把它全部保留爲int
。當然,我可以嘗試通用,通過鍵入類型等,但它只是感覺太複雜,沒有太多的收益。
幾乎所有我想用作下拉列表選項的對象都遵循相同的約定。
是啊......我應該提到的是,隨着可查詢的擴展工作時,你不能使用所有的'CreateMap'可能的選項。你能顯示一個完整的課程清單,你將從你的'Project.To()'聲明中得到你想要的課程,我們可以幫助你弄清楚你需要在你的'CreateMap'中放置什麼? –
@ ScottChamberlain,我已根據您的要求更新了我的答案。 – Gup3rSuR4c