teenup
teenup

Reputation: 7667

Missing type map configuration or unsupported mapping - AutoMapper

I am trying to map an Entity Framework Code First class to a WCF DataContract class using AutoMapper.

The code is as follows:

[DataContract]
public class User
{
    [DataMember]
    public int UserId { get; set; }
    [DataMember]
    public string UserName { get; set; }
    [DataMember]
    public string Password { get; set; }
    [DataMember]
    public string Email { get; set; }
    [DataMember]
    public DateTime DateCreated { get; set; }
    [DataMember]
    public int RoleId { get; set; }
}

public class User1
{
    public int UserId { get; set; }

    [StringLength(255, MinimumLength = 3)]
    public string UserName { get; set; }

    [StringLength(255, MinimumLength = 3)]
    public string Password { get; set; }

    [StringLength(255, MinimumLength = 3)]
    public string Email { get; set; }

    public DateTime DateCreated { get; set; }
    public int RoleId { get; set; }

    [ForeignKey("RoleId")]
    public virtual Role Role { get; set; }
}

public static T Get<T>(this object source) where T : class
{
    Mapper.CreateMap(source.GetType(), typeof(T));
    T destination = default(T);
    Mapper.Map(source, destination);
    return destination;
}

User user = new User();
User1 user1 = user.Get<User1>();

I am getting this exception while executing the last line in above code:

Missing type map configuration or unsupported mapping.

Mapping types: Object -> User
System.Object -> DataLayer.User

Destination path: User

Source value: Service.User

Can anyone help in getting this resolved?

Upvotes: 0

Views: 739

Answers (1)

stuartd
stuartd

Reputation: 73243

Missing type map configuration or unsupported mapping.

Mapping types: Object -> User

This is because you are passing a value of type object, creating a mapping from the underlying type User to type User1, then passing in the object as the source, for which no mapping exists (and the actual error message from the code provided would reference User1 rather than User)

You can just use the overload of Map which allows you to tell AutoMapper what type to use:

Mapper.Map(source, destination, source.GetType(), typeof(T));

Or, if your code allows, use the overload of Map which which allows you to tell AutoMapper what type to use, and also to create the destination object itself:

 return (T)Mapper.Map(source, source.GetType(), typeof(T));

You may want to consider only creating the mapping if required, which would look like this:

public static T Get<T>(this object source)
{
    if (Mapper.FindTypeMapFor(source.GetType(), typeof (T)) == null)
    {
        Mapper.CreateMap(source.GetType(), typeof (T));
    }

    return (T)Mapper.Map(source, source.GetType(), typeof(T));
}

Upvotes: 1

Related Questions