c# - 如何使用 AutoMapper 3 和 Entity Framework 将整数映射到字符串

标签 c# linq entity-framework automapper-3

我正在尝试使用 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/

相关文章:

c# - 读取非英文文件

c# - 用 C# 编写脚本?

c# - 如何在 C# 中表达 VB .NET "Aggregate Into"?

c# - 如何防止另一个应用程序在 C# 中移动 (MS Excel 2010)

c# - 动态创建匿名类型的属性

entity-framework - 最佳实践 - Entity Framework 4 中的数据注释与 OnChanging

c# - 为什么 DefaultIfEmpty 是这样实现的?

c# - 在 select 语句中重用匿名变量

c# - LINQ .FromSQL 错误 InvalidOperationException : Sequence contains more than one matching element

c# - Entity Framework 底层提供者打开失败