2013-10-05 49 views
4

我想使用AutoMapper 3將具有Integer屬性的類投影到具有String屬性的另一個類。如何使用AutoMapper 3和實體框架將Integer映射到字符串

當執行查詢然後我得到以下異常:

System.NotSupportedException:LINQ到實體無法識別方法「System.String的ToString()」方法,而這種方法不能被翻譯成商店表達。

這裏是代碼的相關部分:

public partial class Lookup 
{ 
    public int LookupId { get; set; } 
    public int LookupTypeId { get; set; } 
    public string Value { get; set; } 
    public int SequencialOrder { get; set; } 

    public virtual LookupType LookupType { get; set; } 
} 

public class LookupProfile : Profile 
{ 
    protected override void Configure() 
    { 
     CreateMap<Lookup, SelectListItem>() 
      .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.LookupId.ToString())) 
      .ForMember(dest => dest.Text, opt => opt.MapFrom(src => src.Value)); 

    } 
} 

和查詢的樣子:

Provinces = _db.Lookups.Project().To<SelectListItem>().ToList() 

問:

有沒有一種方法,我可以配置LookupProfile到做適當的映射,並仍然在Linq To Entities中工作? 或者還有另外一種方法可以使投影與Linq to Entities一起工作嗎?

+0

Can not'SelectListItem.Value'是一個整數嗎? –

+0

我的想法完全一樣,但事實證明它不能在這種情況下。我找到了解決方案,並回答了問題 – Elie

回答

3

解決方法是使用SqlFunctions.StringConvert函數。

下面是修改配置文件的代碼,使一切工作:

public class LookupProfile : Profile 
{ 
    protected override void Configure() 
    { 
     CreateMap<Lookup, SelectListItem>() 
      .ForMember(dest => dest.Value, opt => opt.MapFrom(src => SqlFunctions.StringConvert((double)src.LookupId))) 
      .ForMember(dest => dest.Text, opt => opt.MapFrom(src => src.Value)); 

    } 
} 
+1

不錯!也許不妨提一下,這適用於'Project()。To()'語法,因爲映射是作爲轉換爲SQL的表達式來執行的。通過'Mapper.Map',這不起作用。 –

2

我會在這裏萬一別人絆倒在同樣的問題,我不得不離開這個答案。

current accepted answer的一個問題是,如果您在通過助手使用客戶端驗證的ASP.NET MVC項目中,則會爲ID字段(如果是數字)得到驗證錯誤:The field [field] must be a number.發生的原因是SqlFunctions.StringConvert的結果返回一個帶有幾個前導空格的字符串,所以不顯眼的驗證程序不會將其視爲數字。

我解決我自己的這個問題的方法是創建一個通用的SelectListItem<T>類,從SelectListItem繼承,隱藏原來的Value財產,實現了自己的Value二傳手:

public class SelectListItem<T> : SelectListItem 
{ 
    public new T Value { 
     set { 
      base.Value = value.ToString(); 
     } 
     // Kind of a hack that I had to add 
     // otherwise the code won't compile 
     get { 
      return default(T); 
     } 
    } 
} 

然後在Automapper檔案I將映射的項目,像這樣:

public class LookupProfile : Profile 
{ 
    protected override void Configure() 
    { 
     //Use whatever datatype is appropriate: decimal, int, short, etc 
     CreateMap<Lookup, SelectListItem<int>>() 
      .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.LookupId)) 
      .ForMember(dest => dest.Text, opt => opt.MapFrom(src => src.Value)); 

    } 
} 

最後是服務層,我會映射實體的泛型類,並返回一個IEnumerable<SelectListItem>

public IEnumerable<SelectListItem> GetList() { 
    return _db.Lookups.Project().To<SelectListItem<int>>().ToList(); 
} 

這樣你會得到的Value財產權利價值不尾隨空格。

相關問題