在我的项目中,我有一个Linq可查询(实际上是一个EF6集合),我需要将其转换为数据传输对象的集合。我在整个项目中都使用了AutoMapper
,特别是它能够执行类型投影,从而减少了Linq查询生成的SQL数量。当投影到可为空的枚举时,AutoMapper抛出异常
但是我的一个DTO类有一个小问题。关联的数据库列包含一个可以为空的字符串,我希望将其映射为可空的枚举。但在运行时抛出异常
在类型'System.String'和'System.Nullable`1 [AutomapperEnumTest.Method]'之间未定义强制运算符。
下面是一个完整的测试程序演示该问题:(见.Net Fiddle)
using System;
using System.Linq;
using AutoMapper;
using AutoMapper.QueryableExtensions;
namespace AutomapperEnumTest
{
public class Program
{
public static void Main()
{
Configure();
var src = new SourceType[] { new SourceType { Name = "Rob", MethodName = "AUTO" } };
var results = src.AsQueryable()
.ProjectTo<DestType>();
foreach(var item in results)
{
Console.WriteLine(String.Format("DestType Name={0} Method={1}", item.Name, item.Method));
}
Console.WriteLine("Done");
}
private static void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<string, Method?>().ProjectUsing(src => src == "MANUAL" ? Method.MANUAL : Method.AUTO);
cfg.CreateMap<SourceType, DestType>()
.ForMember(dest => dest.Method, opt => opt.MapFrom(src => src.MethodName));
});
}
}
public enum Method
{
MANUAL=0,
AUTO=1
}
public class DestType
{
public string Name {get; set; }
public Method? Method {get; set; }
}
public class SourceType
{
public string Name {get; set; }
public string MethodName {get; set; }
}
}
现在,如果我的属性更改从Method?
到Method
正常工作(见.Net Fiddle此修改)。但我不想这样做,所以我的问题是如何通知Linq/AutoMapper它应该使用我的ProjectUsing
作为可空的枚举?
非常感谢。
感谢您提供这样一个完整的答案。我测试过了,这确实解决了这个问题。 – Rob