简体   繁体   English

将MyType类型映射到MyType时出现InvalidCastException

[英]InvalidCastException while Mapping types MyType to MyType

I'm using AutoMapper 2.2.1 to map different business objects to view models. 我正在使用AutoMapper 2.2.1将不同的业务对象映射到视图模型。 Now I'm getting a InvalidCastExceptions if I try to map objects which have a property of type CustomList (see code below). 现在,如果我尝试映射具有CustomList类型属性的对象,我将获得InvalidCastExceptions (请参阅下面的代码)。 The exception says that CustomList cannot be casted to IList . 例外情况说CustomList无法转换为IList Which is correct because CustomList implements IReadOnlyList and not IList . 这是正确的,因为CustomList实现IReadOnlyList而不是IList

So why automapper tries to cast it in this manner and how to fix/workaround this? 那么为什么automapper试图以这种方式投射它以及如何修复/解决这个问题呢?

I have these types: 我有这些类型:

public class MyViewModel : SomeModel { //... some addtional stuff ...}

public class SomeModel {
public CustomList DescriptionList { get; internal set; }
}

public class CustomList : ReadOnlyList<SomeOtherModel> {}

public abstract class ReadOnlyList<TModel> : IReadOnlyList<TModel> {}

//map it
//aList is type of SomeModel 
var viewList = Mapper.Map<List<MyViewModel>>(aList);

Having your class implement from IReadOnlyList is most likely causing the problem. 从IReadOnlyList获得类实现很可能导致问题。 Automapper doesn't know how to map a read-only list to a read-only list. Automapper不知道如何将只读列表映射到只读列表。 It creates new instances of objects, and there is no add method or collection initializer for IReadOnlyList. 它创建了对象的新实例,并且没有IReadOnlyList的添加方法或集合初始值设定项。 Automapper needs to be able to access the underlying list the readonly list is wrapping around. Automapper需要能够访问readonly列表所包含的基础列表。 This can be done using the ConstructUsing method. 这可以使用ConstructUsing方法完成。

Updated List Model: 更新列表模型:

public class CustomList : IReadOnlyList<string>
{
    private readonly IList<string> _List;

    public CustomList (IList<string> list)
    {
        _List = list;
    }

    public CustomList ()
    {
        _List = new List<string>();
    }

    public static CustomList CustomListBuilder(CustomList customList)
    {
        return new CustomList (customList._List);
    }
}

Updated automapper config 更新了automapper配置

Mapper.CreateMap<CustomList, CustomList>().ConstructUsing(CustomList.CustomListBuilder);

This is a simple example but I was able to get it to map properly as well as not throw an exception. 这是一个简单的例子,但我能够正确地映射它并且不抛出异常。 This isn't the best code, doing this would result in the same list being referenced by two different readonly lists (depending on your requirements, that may or may not be okay). 这不是最好的代码,这样做会导致同一个列表被两个不同的只读列表引用(取决于您的要求,可能会也可能不会)。 Hopefully this helps. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM