Convert a string value to an entity in Automapper

I am trying to figure out how to use Automapper when my entity has a field of type entity.
I've got 3 classes like these:

public abstract class Entity<IdK> 
{
    public virtual IdK Code { get; protected set; }
}

public class Contact : Entity
{
    public virtual string Name { get; set; }
    public virtual Company Company { get; set; }
}

public class Company : Entity
{
    public virtual string Name { get; set; }
}

My class Contact contain an element of type Company.
I've also created a ViewModel to trasfer some infos to my view:

public ContactViewModel()
{
        public Guid Code { get; set; }
        public int Version { get; set; }

        [DisplayName("Contact")]
        public string Name { get; set; }

        [DisplayName("Company")]
        public string Company { get; set; }
}

In my viewmodel I've defined a field Company of type string. This is going to contain a value the user will chose from a dropdown (list of companies).

I've defined a bootstrapper when my App starts:

public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x => {
                x.CreateMap<Domain.Contact, ViewModels.ContactViewModel>();
                x.CreateMap<ViewModels.ContactViewModel, Domain.Contact>()
            });
        }
    }

When I try to remap my ViewModel to my entity I get a conversion error (AutoMapper.AutoMapperMappingException). Automapper can't figure out how to convert my Company (string) into an object of type Company, member of Contact. Is it possible to define a rule so that Automapper know how to transform the string (company) into the code of my Company object, member of Contact?


You need to use a Resolver. Something like:

public class CompanyTypeResolver : ValueResolver<string, Company>
{
    protected override Company ResolveCore(string name)
    {
        return new Company {Name = name};
    }
}

Then in mapping code you call it like:

.ForMember(dto => dto.Company, opt => opt.ResolveUsing<CompanyTypeResolver>().FromMember(src => src.Name))
链接地址: http://www.djcxy.com/p/37422.html

上一篇: Automapper实例化目标对象,而不是递归地映射

下一篇: 将字符串值转换为Automapper中的实体