2014-03-29 43 views
0

我想將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。當然,我可以嘗試通用,通過鍵入類型等,但它只是感覺太複雜,沒有太多的收益。

幾乎所有我想用作下拉列表選項的對象都遵循相同的約定。

+0

是啊......我應該提到的是,隨着可查詢的擴展工作時,你不能使用所有的'CreateMap'可能的選項。你能顯示一個完整的課程清單,你將從你的'Project.To ()'聲明中得到你想要的課程,我們可以幫助你弄清楚你需要在你的'CreateMap'中放置什麼? –

+0

@ ScottChamberlain,我已根據您的要求更新了我的答案。 – Gup3rSuR4c

回答

1

試試這個轉換器

public class ByteToInt32Converter : ITypeConverter<byte, int> 
    { 
     public int Convert(ResolutionContext context) 
     { 
      return System.Convert.ToInt32(context.SourceValue); 
     } 
    } 

Mapper.CreateMap<byte, int>().ConvertUsing<ByteToInt32Converter>(); 

// your Company to SelectItem mapping code. 
+0

這沒有奏效。我懷疑的是,我認爲斯科特也懷疑的原因是轉爐本身不是問題。事實上,我認爲它工作得很好,但是,AutoMapper根本就沒有調用它。也許某種方式不匹配? – Gup3rSuR4c

+0

實際上Alex,對於byte到int,你根本不需要顯式轉換。 AutoMapper不應該抱怨。你可以請任何自定義轉換器代碼,並試試這個:var si = Mapper.Map (company);讓我們知道導致異常的確切調用代碼。 –

+0

是的,我也想知道,但不過,它正在對我大吼。話雖如此,「公司」是一個實體框架的代理對象,這可能與它有什麼關係? – Gup3rSuR4c