AutoMapper:如何从字符串中解析 Int 并可以根据数据类型创建规则?

2024-03-24

我的表单有两个模型,一个是指向它的 ViewModel,另一个是来自它的 ControlModel。 ControlModel 具有所有相同的字段名称和层次结构,但所有字段都是字符串数据类型。

如何编写 AutoMapper 代码以将字符串字段转换为整数?我尝试了 Int32.Parse(myString) 但 Int32 在表达式中不可用(给出错误)。

Mapper.CreateMap<SourceClass, DestinationClass>()
      .ForMember(dest => dest.myInteger, 
                  opt => opt.MapFrom(src => src.myString));

类中的类型及其对应的转换类型:

字符串转换为 int、int?、double、double?、DateTime 和 bool

此外,是否有任何方法可以用该函数解析目标中的所有整数来概括映射?换句话说,有没有办法为数据类型创建映射?

EDIT:

这看起来很有希望:

AutoMapper.Mapper.CreateMap<string, int>()
          .ConvertUsing(src => Convert.ToInt32(src));

编辑: 这post https://stackoverflow.com/questions/2560741/automapper-type-converter-from-string-to-ienumerablestring-is-not-being-called真的很有帮助


我最终做了这样的事情:

Mapper.CreateMap<string, int>().ConvertUsing<IntTypeConverter>();
Mapper.CreateMap<string, int?>().ConvertUsing<NullIntTypeConverter>();
Mapper.CreateMap<string, decimal?>().ConvertUsing<NullDecimalTypeConverter>();
Mapper.CreateMap<string, decimal>().ConvertUsing<DecimalTypeConverter>();
Mapper.CreateMap<string, bool?>().ConvertUsing<NullBooleanTypeConverter>();
Mapper.CreateMap<string, bool>().ConvertUsing<BooleanTypeConverter>();
Mapper.CreateMap<string, Int64?>().ConvertUsing<NullInt64TypeConverter>();
Mapper.CreateMap<string, Int64>().ConvertUsing<Int64TypeConverter>();
Mapper.CreateMap<string, DateTime?>().ConvertUsing<NullDateTimeTypeConverter>();
Mapper.CreateMap<string, DateTime>().ConvertUsing<DateTimeTypeConverter>();

Mapper.CreateMap<SourceClass, DestClass>();

Mapper.Map(mySourceObject, myDestinationObject);

以及它引用的类(初稿):

// TODO: Boil down to two with Generics if possible
#region AutoMapTypeConverters
// Automap type converter definitions for 
// int, int?, decimal, decimal?, bool, bool?, Int64, Int64?, DateTime
// Automapper string to int?
private class NullIntTypeConverter : TypeConverter<string, int?>
{   protected override int? ConvertCore(string source)
    {   if (source == null)
            return null;
        else
        {   int result;
            return Int32.TryParse(source, out result) ? (int?) result : null;
}   }   }
// Automapper string to int
private class IntTypeConverter : TypeConverter<string, int>
{   protected override int ConvertCore(string source)
    {   if (source == null)
            throw new MappingException("null string value cannot convert to non-nullable return type.");
        else
            return Int32.Parse(source); 
}   }
// Automapper string to decimal?
private class NullDecimalTypeConverter : TypeConverter<string, decimal?>
{   protected override decimal? ConvertCore(string source)
    {   if (source == null)
            return null;
        else
        {   decimal result;
            return Decimal.TryParse(source, out result) ? (decimal?) result : null;
}   }   }
// Automapper string to decimal
private class DecimalTypeConverter : TypeConverter<string, decimal>
{   protected override decimal ConvertCore(string source)
    {   if (source == null)
            throw new MappingException("null string value cannot convert to non-nullable return type.");
        else
            return Decimal.Parse(source); 
}   }
// Automapper string to bool?
private class NullBooleanTypeConverter : TypeConverter<string, bool?>
{   protected override bool? ConvertCore(string source)
    {   if (source == null)
            return null;
        else
        {   bool result;
            return Boolean.TryParse(source, out result) ? (bool?) result : null;
}   }   }
// Automapper string to bool
private class BooleanTypeConverter : TypeConverter<string, bool>
{   protected override bool ConvertCore(string source)
    {   if (source == null)
            throw new MappingException("null string value cannot convert to non-nullable return type.");
        else
            return Boolean.Parse(source); 
}   }
// Automapper string to Int64?
private class NullInt64TypeConverter : TypeConverter<string, Int64?>
{   protected override Int64? ConvertCore(string source)
    {   if (source == null)
            return null;
        else
        {   Int64 result;
            return Int64.TryParse(source, out result) ? (Int64?)result : null;
}   }   }
// Automapper string to Int64
private class Int64TypeConverter : TypeConverter<string, Int64>
{   protected override Int64 ConvertCore(string source)
    {   if (source == null)
            throw new MappingException("null string value cannot convert to non-nullable return type.");
        else
            return Int64.Parse(source); 
}   }
// Automapper string to DateTime?
// In our case, the datetime will be a JSON2.org datetime
// Example: "/Date(1288296203190)/"
private class NullDateTimeTypeConverter : TypeConverter<string, DateTime?>
{   protected override DateTime? ConvertCore(string source)
    {   if (source == null)
            return null;
        else
        {   DateTime result;
            return DateTime.TryParse(source, out result) ? (DateTime?) result : null;
}   }   }
// Automapper string to DateTime
private class DateTimeTypeConverter : TypeConverter<string, DateTime>
{   protected override DateTime ConvertCore(string source)
    {   if (source == null)
            throw new MappingException("null string value cannot convert to non-nullable return type.");
        else
            return DateTime.Parse(source); 
}   }
#endregion
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AutoMapper:如何从字符串中解析 Int 并可以根据数据类型创建规则? 的相关文章

  • SharpZipLib - 将文件夹/目录添加到 zip 存档

    通过示例 我很好地掌握了如何提取 zip 文件 几乎在每个示例中 识别 ZipEntry 是否为目录的方法如下 string directoryName Path GetDirectoryName theEntry Name string
  • 如何从RichTextBox中获取显示的文本?

    如何获得显示的RichTextBox 中的文本 我的意思是 如果 RichTextBox 滚动到末尾 我只想接收那些对我来说可见的行 P S 获得第一个显示的字符串就足够了 您想使用 RichTextBox GetCharIndexFrom
  • 如何使用 MVVM 更新 WPF 中编辑的数据? [复制]

    这个问题在这里已经有答案了 我正在为聊天应用程序构建 UI 设计 在尝试更新所选联系人的消息时遇到问题 选择现有联系人 选择编辑选项 然后编辑其属性 例如用户名和图像 后 唯一进行的更改是联系人的用户名和图像 我仍然想更改 MessageM
  • 键盘加速器在 UWP 应用中停止工作

    我正在尝试将键盘加速器添加到 UWP 应用程序中的 CommandBar 菜单项 当应用程序启动时 这工作正常 但在我第一次打开溢出菜单后 加速器停止工作 这似乎不会发生在主要命令 菜单之外 上 只有溢出菜单内的辅助命令才会发生 此外 单击
  • 为什么这个函数指针赋值在直接赋值时有效,但在使用条件运算符时无效?

    本示例未使用 include 在 MacOS10 14 Eclipse IDE 上编译 使用 g 选项 O0 g3 Wall c fmessage length 0 假设这个变量声明 int fun int 这无法通过 std touppe
  • 如何在不实例化一个类的情况下检查它是否继承了另一个类? [复制]

    这个问题在这里已经有答案了 假设我有一个如下所示的类 class Derived some inheritance stuff here 我想在我的代码中检查类似的内容 Derived is SomeType 但看起来像is运算符需要 De
  • 如何在编译C代码时禁用警告?

    我正在使用 32 位 Fedora 14 系统 我正在使用编译我的源代码gcc 有谁知道如何在编译c代码时禁用警告 EDIT 是的 我知道 最好的办法是修复这些警告以避免任何未定义 未知的行为 但目前在这里 我第一次编写了巨大的代码 并且在
  • 如何使用 wpf webbrowser 将数据发布到 Web 服务器

    我想从数据库获取数据并使用它来让用户登录到网站 我有一个包含 Web 浏览器控件的 wpf 页面 我有这样的代码 用于将用户登录到用 php 编写的网站
  • 默认值 C# 类 [重复]

    这个问题在这里已经有答案了 我在控制器中有一个函数 并且我收到表单的信息 我有这个代码 public Actionresult functionOne string a string b string c foo 我尝试将其转换为类似的类
  • 我可以仅在少数情况下关闭模拟吗

    我有一个始终使用模拟的应用程序 但是 当用户以管理员身份登录时 一些操作需要他们写入服务器本身 现在 如果这些用户在实际服务器上没有权限 有些用户没有 则不会让他们写入 我想做的是关闭几个命令的模拟 有没有办法做这样的事情 using Ho
  • C# datagridview 列转入数组

    我正在用 C 构建一个程序 并在其中包含一个 datagridview 组件 datagridview 有固定数量的列 2 我想将其保存到两个单独的数组中 但行数确实发生了变化 我怎么能这样做呢 假设一个名为 dataGridView1 的
  • 在简单注入器中注册具有多个构造函数和字符串依赖项的类型

    我正在尝试弄清楚如何使用 Simple Injector 我在项目中使用了它 注册简单服务及其组件没有任何问题 但是 当组件具有两个以上实现接口的构造函数时 我想使用依赖注入器 public DAL IDAL private Logger
  • 如何用 C 语言练习 Unix 编程?

    经过五年的专业 Java 以及较小程度上的 Python 编程并慢慢感觉到我的计算机科学教育逐渐消失 我决定要拓宽我的视野 对世界的一般用处 并做一些 对我来说 感觉更重要的事情就像我真的对机器有影响一样 我选择学习 C 和 Unix 编程
  • 系统错误 124 - SHFileOperation 的 ERROR_INVALID_LEVEL

    我在使用时遇到问题SHFileOperation SHFileOperation SHFILEOPSTRUCT https stackoverflow com questions 9191415 shfileoperation shfile
  • 如何使用收益返回和递归获得字母的每个组合?

    我有几个像这样的字符串列表 可能有几十个列表 1 A B C 2 1 2 3 3 D E F 这三个仅作为示例 用户可以从几十个具有不同数量元素的类似列表中进行选择 再举个例子 这对于用户来说也是一个完全有效的选择 25 empty 4 1
  • 如何访问窗口?

    我正在尝试使用其句柄访问特定窗口 即System IntPtr value Getting the process of Visual Studio program var process Process GetProcessesByNam
  • #pragma pack(16) 和 #pragma pack(8) 的效果总是相同吗?

    我正在尝试使用来对齐数据成员 pragma pack n http msdn microsoft com en us library 2e70t5y1 28v vs 100 29 aspx 以下面为例 include
  • C++ [Windows] 可执行文件所在文件夹的路径[重复]

    这个问题在这里已经有答案了 我需要访问一些文件fstream在我的 Windows 上的 C 应用程序中 这些文件都位于我的exe文件所在文件夹的子文件夹中 获取当前可执行文件的文件夹路径的最简单且更重要的 最安全的方法是什么 Use 获取
  • C# 粘贴到文本框时检查剪贴板中的字符

    有没有一些方法可以在粘贴到文本框 C 之前仅检查剪贴板中的字符 Ctrl V 和右键单击 gt 粘贴 但不使用 MaskedTextbox 在文本框文本更改中添加规则以仅接受数字 例如 private string value privat
  • c# 模拟 IFormFile CopyToAsync() 方法

    我正在对一个异步函数进行单元测试 该函数将 IFormFile 列表转换为我自己的任意数据库文件类列表 将文件数据转换为字节数组的方法是 internal async Task

随机推荐