我正在尝试使用 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 to Entities 一起工作?
最佳答案
解决方案是使用 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));
}
}
关于c# - 如何使用 AutoMapper 3 和 Entity Framework 将整数映射到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19198572/