簡體   English   中英

如何使用AutoMapper 3和Entity Framework將Integer映射到String

[英]How to map Integer to String with AutoMapper 3 and Entity Framework

我試圖使用AutoMapper 3將具有Integer屬性的類投影到另一個具有String屬性的類。

執行查詢時,我得到以下異常:

System.NotSupportedException:LINQ to Entities無法識別方法'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與實體一起投影?

解決方案是使用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));

    }
}

我會在這里留下這個答案,以防其他人偶然發現我遇到的同樣問題。

當前接受的答案的一個問題是,如果您使用通過幫助程序進行客戶端驗證的ASP.NET MVC項目,您將獲得ID字段的驗證錯誤(如果它是一個數字): The field [field] must be a number. 發生這種情況是因為SqlFunctions.StringConvert的結果返回一個帶有幾個前導空格的字符串,因此不顯眼的驗證器不會將其視為數字。

我自己解決這個問題的方法是創建一個繼承自SelectListItem的通用SelectListItem<T>類,隱藏原始的Value屬性並實現自己的Value setter:

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配置文件中,我會像這樣映射項目:

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));

    }
}

最后在Service層,我將實體映射到泛型類並返回IEnumerable<SelectListItem>

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

這樣,您將獲得Value屬性的正確值,而不會有尾隨空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM