InvalidCastException when mapping IReadOnlyDictionary<int, int> to the same type
See original GitHub issueSource/destination types
public class Source
{
public IReadOnlyDictionary<int, int> Values { get; set; }
}
public class Destination
{
public IReadOnlyDictionary<int, int> Values { get; set; }
}
Mapping configuration
var mapper = new MapperConfiguration(config =>
{
config.CreateMap<Source, Destination>();
}).CreateMapper();
Version: 7.0.1
Expected behavior
Should successfully map Source.Values
to Destination.Values
.
Actual behavior
Throws AutoMapperMappingException
:
Error mapping types.
Mapping types: Source -> Destination UserQuery+Source -> UserQuery+Destination
Type Map configuration: Source -> Destination UserQuery+Source -> UserQuery+Destination
Property: Values
(UserQuery
is the root class in a LINQPad query)
Inner exception: InvalidCastException
:
Unable to cast object of type ‘System.Collections.Generic.List
1[System.Collections.Generic.KeyValuePair
2[System.Int32,System.Int32]]’ to type ‘System.Collections.Generic.IReadOnlyDictionary`2[System.Int32,System.Int32]’.
Steps to reproduce
var source = new Source
{
Values = new Dictionary<int, int> { [1] = 42 }
};
var destination = mapper.Map<Destination>(source);
Issue Analytics
- State:
- Created 5 years ago
- Comments:15 (14 by maintainers)
Top Results From Across the Web
InvalidCastException with Dictionary in C# - Stack Overflow
First, check that rdr["artikel_id"] and rdr["sum(aantal)"] are both not null. If they both are not null, verify their runtime type by doing ...
Read more >How to initialize a dictionary with a collection initializer - C# ...
Learn how to initialize a dictionary in C#, using either the Add method or an index initializer. This example shows both options.
Read more >Dictionary<TKey,TValue> Class
The Dictionary<TKey,TValue> generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists...
Read more >C# | How to convert an ArrayList to Array
If the ArrayList doesn't contain the elements of the same type then your conversion(ArrayList to Array) will throw InvalidCastException.
Read more >Bidirectional Map in C# - Code Review Stack Exchange
If TFirst and TSecond are the same, nearly all of the API becomes useless because the compiler can't disambiguate the method calls.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I’m gonna add a new issue for this one, for tracking purposes.
I doubt it. If you’ll give it some thought it should be easy to do.