AutoMapper自定义TypeConverter不工作

本文关键字:工作 TypeConverter 自定义 AutoMapper | 更新日期: 2023-09-27 17:54:38

我试图将AutoMapper集成到我的项目中,它主要是工作,现在我知道如何项目EntityFramework对象,但我一直得到这个异常:无法从系统创建一个映射表达式。字节到System.Int32。所以,我想我会做一个自定义类型转换器它会工作,除了它不:

public sealed class ByteToInt32Converter : TypeConverter<byte, int> {
    protected override int ConvertCore(
        byte source) {
        return (int)source;
    }
}
Mapper.CreateMap<byte, int>().ConvertUsing<ByteToInt32Converter>();

查看文档和其他搜索结果,这应该是正确的,但我仍然得到一个异常。做什么?

根据Scott的请求,这是我的源对象Company和目标对象SelectItem:

public partial class Company {
    public byte Id { get; set; }
    public string Name { get; set; }
    #region Relationship Properties
    public byte? ParentCompanyId { get; set; }
    public virtual ICollection<Company> Companies { get; private set; }
    public virtual ICollection<Employee> Employees { get; private set; }
    public virtual Company ParentCompany { get; set; }
    public virtual ICollection<State> States { get; private set; }
    #endregion
    public Company() {
        this.Companies = new List<Company>();
        this.Employees = new List<Employee>();
        this.States = new List<State>();
    }
}
public sealed class SelectItem : ISelectItem {
    public string Key { get; set; }
    public int Value { get; set; }
}
public interface ISelectItem : IItem {
    string Key { get; set; }
    int Value { get; set; }
}
public interface IItem {
}

下面是映射代码:

Mapper.CreateMap<Company, SelectItem>()
    .ForMember(
        d => d.Key,
        o => o.MapFrom(
            s => s.Name))
    .ForMember(
        d => d.Value,
        o => o.MapFrom(
            s => s.Id));

我基本上试图将Company对象扁平化为一个"键值对"对象,我可以将其传递到MVC Html.DropDownList()。我并没有特别注意匹配Key Id的类型,因为我只使用它来生成下拉列表,所以我只是把它全部保留为int。当然,我可以尝试泛型,传递键类型,等等,但它只是感觉太复杂了,没有太多的收益。

几乎所有我想用作下拉列表选项的对象都遵循相同的约定

AutoMapper自定义TypeConverter不工作

试试这个转换器

 public class ByteToInt32Converter : ITypeConverter<byte, int>
    {
        public int Convert(ResolutionContext context)
        {
            return System.Convert.ToInt32(context.SourceValue);
        }
    }
Mapper.CreateMap<byte, int>().ConvertUsing<ByteToInt32Converter>();
// your Company to SelectItem mapping code.