我正在创建一个简单的 MVC4 应用程序
我有一个自动映射器
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => src.Stringphoneno));
IntphoneNo 是数据类型int(IntphoneNo 是我的类Person
的一个变量)
源属性 Stringphoneno 的数据类型为 string。
当我映射时,出现以下错误。
An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code
但是当我将 IntphoneNo 的数据类型从 int 更改为 string 时,我的程序运行成功。
不幸的是,我无法更改模型中的数据类型
有什么方法可以改变映射中的 Datatupe .. 像下面这样的东西
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => src.Int32(Stringphoneno));
经过一些研究,我又向前迈进了一步..
如果我的 StringPhoneNo 是 = 123456
然后下面的代码正在工作。我不需要将它解析为字符串
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => src.Stringphoneno));
但是当我的 StringPhoneNo 为 = 12 3456(12 之后有一个空格)时,我的代码无法正常工作。 有什么方法可以在 automapper 中修剪 Stringphoneno 中的空格(Stringphoneno 我从 webservice 获取)。
类似下面的内容..
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => src.Trim(Stringphoneno)));
最佳答案
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => int.Parse(src.Stringphoneno)));
这是一些使用所描述 map 的示例工作代码
class SourceClass
{
public string Stringphoneno { get; set; }
}
class DestinationClass
{
public int IntphoneNo { get; set; }
}
var source = new SourceClass {Stringphoneno = "8675309"};
var destination = Mapper.Map<SourceClass, DestinationClass>(source);
Console.WriteLine(destination.IntphoneNo); //8675309
关于c# - 自动映射器从字符串转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767410/