I'm trying to integrate AutoMapper into my project and it's mostly working out, now that I know how to project EntityFramework objects , but I keep getting this exception: Unable to create a map expression from System.Byte to System.Int32 . So, I figure I'll make a custom type converter and it will work, except it doesn't:
public sealed class ByteToInt32Converter : TypeConverter<byte, int> {
protected override int ConvertCore(
byte source) {
return (int)source;
}
}
Mapper.CreateMap<byte, int>().ConvertUsing<ByteToInt32Converter>();
Looking at the documentation and other search results, this should be correct, but I'm still getting an exception. What do?
Update
Per Scott's request, here's my source object, Company
, and the destination object 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 {
}
And here's the mapping code:
Mapper.CreateMap<Company, SelectItem>()
.ForMember(
d => d.Key,
o => o.MapFrom(
s => s.Name))
.ForMember(
d => d.Value,
o => o.MapFrom(
s => s.Id));
I'm basically trying to flatten the Company
object down to a "key-value pair" object that I can pass into the MVC Html.DropDownList()
. I didn't particularly care to match the types of the Key Id since I was only using it to generate the drop down list so I just left it all as int
. Granted, I could try to be generic, pass in the key type, etc, but it just feels way too complicated for not much gain.
Pretty much all of the objects I would want to use as drop down list options, follow the same convention.
Try this converter
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.