C# 自动映射器从字符串转换为 Int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18767410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto Mapper convert from string to Int
提问by user2739679
I am creating a simple MVC4 application
我正在创建一个简单的 MVC4 应用程序
I have a automapper
我有一个自动映射器
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => src.Stringphoneno));
IntphoneNois of DataType int( IntphoneNo is an variable of my class Person
)
Source attribute Stringphonenois of Datatype string.
IntphoneNo是数据类型int(IntphoneNo 是我的类的变量Person
)源属性Stringphoneno是数据类型字符串。
When i am mapping , i am getting follwoing error.
当我映射时,出现以下错误。
An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code
AutoMapper.dll 中发生了“AutoMapper.AutoMapperMappingException”类型的异常,但未在用户代码中处理
But when i am changing the Dataype of IntphoneNofrom intto stringthen my program is running successfully.
但是当我将 IntphoneNo 的Dataype从int更改为string 时,我的程序运行成功。
Unfortunately i cant change the Datatype inmy model
不幸的是,我无法在我的模型中更改数据类型
Is theer any way to change Datatupe in mapping .. Something like below
有没有办法在映射中更改 Datatupe .. 如下所示
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => src.Int32(Stringphoneno));
After some research I came one step futher ..
If my StringPhoneNo is = 123456
then follwoing code is working. I dont need to parse it to string
经过一番研究,我又向前迈进了一步。
如果我的 StringPhoneNo 是 = 123456,
那么以下代码正在运行。我不需要将其解析为字符串
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => src.Stringphoneno));
but when my StringPhoneNo is = 12 3456 ( there is a space after 12) then my code is not working. Is there any way to trim spaces in Stringphoneno (Stringphonenoi am geting from webservice) in automapper.
但是当我的 StringPhoneNo 是 = 12 3456 ( 12之后有一个空格)时,我的代码不起作用。有什么方法可以在 automapper 中修剪 Stringphoneno(我从 webservice获取的 Stringphoneno)中的空格。
Something like below..
像下面这样..
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => src.Trim(Stringphoneno)));
采纳答案by Yuriy Faktorovich
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.IntphoneNo,
opt => opt.MapFrom(src => int.Parse(src.Stringphoneno)));
Here is some sample working code using the map described
以下是使用描述的地图的一些示例工作代码
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
回答by Alexei
Yuriy Faktorovich
's solution can be generalized for all string
s that should be converted to int
s by defining an extension method for IMappingExpression
and usage of some custom attribute:
Yuriy Faktorovich
通过定义一些自定义属性的扩展方法和用法,可以将 的解决方案推广到所有string
应该转换为int
s 的 s IMappingExpression
:
[AttributeUsage(AttributeTargets.Property)]
public class StringToIntConvertAttribute : Attribute
{
}
// tries to convert string property value to integer
private static int GetIntFromString<TSource>(TSource src, string propertyName)
{
var propInfo = typeof(TSource).GetProperty(propertyName);
var reference = (propInfo.GetValue(src) as string);
if (reference == null)
throw new MappingException($"Failed to map type {typeof(TSource).Name} because {propertyName} is not a string);
// TryParse would be better
var intVal = int.Parse(reference);
return intVal;
}
public static IMappingExpression<TSource, TDestination> StringToIntMapping<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var srcType = typeof(TSource);
foreach (var property in srcType.GetProperties().Where(p => p.GetCustomAttributes(typeof(StringToIntConvertAttribute), inherit: false).Length > 0))
{
expression.ForMember(property.Name, opt => opt.MapFrom(src => GetIntFromString(src, property.Name)));
}
return expression;
}
In order to make this work, the following steps must be performed:
为了使这项工作,必须执行以下步骤:
Mapping between source and destination must append the mapping extension. E.g.:
var config = new MapperConfiguration(cfg => { // other mappings cfg.CreateMap<SrcType, DestType>().StringToIntMapping(); });
Apply the attribute to all source string properties that must automatically be converted to integer values
源和目标之间的映射必须附加映射扩展。例如:
var config = new MapperConfiguration(cfg => { // other mappings cfg.CreateMap<SrcType, DestType>().StringToIntMapping(); });
将该属性应用于必须自动转换为整数值的所有源字符串属性
回答by WhizBang
The problem you may face is when it is unable to parse the string, one option would be to use a ResolveUsing:
您可能面临的问题是当它无法解析字符串时,一种选择是使用 ResolveUsing:
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.intphoneno, opts => opts.ResolveUsing(src =>
double.TryParse(src.strphoneno, out var phoneNo) ? phoneNo : default(double)));
回答by Mitch Stewart
Here's a simpler, but less scalable approach. Whenever you call Mapper.Initialize, remember to call .ToInt() or you'll get a run time error.
这是一种更简单但可扩展性较差的方法。每当您调用 Mapper.Initialize 时,请记住调用 .ToInt() 否则您将收到运行时错误。
public class NumberTest
{
public static void Main(string[] args)
{
Console.WriteLine("".ToInt());
// 0
Console.WriteLine("99".ToInt());
// 99
}
}
public static class StringExtensions
{
public static int ToInt(this string text)
{
int num = 0;
int.TryParse(text, out num);
return num;
}
}
// Use like so with Automapper
.ForMember(dest => dest.WidgetID, opts => opts.MapFrom(src => src.WidgetID.ToInt()));