gpt4 book ai didi

c# - AutoMapper Enum to byte with implementation Mapper Configurator

转载 作者:行者123 更新时间:2023-12-04 02:32:42 24 4
gpt4 key购买 nike

枚举定义是

public enum RowStatusEnum
{
Modified = 1,
Removed = 2,
Added = 3
}

public class RowStatusEnumConvertor : IMapperConfigurator
{
public void Cofigure()
{
Mapper.CreateMap<RowStatusEnum, byte>();
Mapper.CreateMap<byte, RowStatusEnum >();
}
}

我在 RowStatusEnumConvertor 类中使用实现 IMapperConfigurator 配置 autoMapper,
但不能运行这段代码,也不能映射这种类型,我认为我的配置不正确或不够,
请帮我

谢谢

最佳答案

这样的事情对你有用吗?

Classes.cs

namespace StackOverflow.RowStatus
{
public enum RowStatusEnum
{
Modified = 1,
Removed = 2,
Added = 3
}
}

AutoMapperConfigurator.cs

namespace StackOverflow.RowStatus
{
using System;
using System.Linq;

using AutoMapper;

public class MyProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<byte, RowStatusEnum>().ConvertUsing(
x => Enum.GetValues(typeof(RowStatusEnum))
.Cast<RowStatusEnum>().First(y => (byte)y == x));
Mapper.CreateMap<RowStatusEnum, byte>().ConvertUsing(
x => (byte)x);
}
}
}

MappingTests.cs

namespace StackOverflow.RowStatus
{
using AutoMapper;

using NUnit.Framework;

[TestFixture]
public class MappingTests
{
[Test]
public void AutoMapper_Configuration_IsValid()
{
Mapper.Initialize(m => m.AddProfile<MyProfile>());
Mapper.AssertConfigurationIsValid();
}

[TestCase(1, Result = RowStatusEnum.Modified)]
[TestCase(2, Result = RowStatusEnum.Removed)]
[TestCase(3, Result = RowStatusEnum.Added)]
public RowStatusEnum AutoMapper_ConvertFromByte_IsValid(
byte rowStatusEnum)
{
Mapper.Initialize(m => m.AddProfile<MyProfile>());
Mapper.AssertConfigurationIsValid();
return Mapper.Map<byte, RowStatusEnum>(rowStatusEnum);
}

[TestCase(RowStatusEnum.Modified, Result = 1)]
[TestCase(RowStatusEnum.Removed, Result = 2)]
[TestCase(RowStatusEnum.Added, Result = 3)]
public byte AutoMapper_ConvertFromEnum_IsValid(
RowStatusEnum rowStatusEnum)
{
Mapper.Initialize(m => m.AddProfile<MyProfile>());
Mapper.AssertConfigurationIsValid();
return Mapper.Map<RowStatusEnum, byte>(rowStatusEnum);
}
}
}

关于c# - AutoMapper Enum to byte with implementation Mapper Configurator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14108080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com