How to map Integer to String using AutoMapper 3 and Entity Framework

I am trying to use AutoMapper 3 to project a class using the Integer property into another class with the String property.

When the request is executed, I get the following exception:

System.NotSupportedException: LINQ to Entities does not recognize the 'System.String ToString ()' method, and this method cannot be translated into a storage expression.

Here are the relevant parts of the code:

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

    }
}

And the request looks like this:

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

Question:

Is there a way to configure LookupProfile to display correctly and still work inside Linq To Entities? Or is there another way to get a projection to work with Linq in Entities?

+4
2

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

    }
}
+3

, - , .

, 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 :

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 .

+2

All Articles