简体   繁体   中英

AutoMapper - how do you map to property names based on class names?

By convention, the database I'm using has its table name included in the ID eg the ID of an Employee table => EmployeeID.

Is it possible to use AutoMapper to wire up a convention to map {Source}.[SourceClassName]ID => {Destination}.Id and vice-versa?

By convention, I mean can I add a general rule for the profile, so that I don't have to include it in every map that is created.

I'm using AutoMapper 5.2.0.

Yes you can easily do this. There is an overload where you pass in the source type and the Destination type. For instance:

_config.CreateMap(SourceType, DestinationType)

Just get the types by name:

    private static Type FindType(string fullName)
{
    return
        AppDomain.CurrentDomain.GetAssemblies()
            .Where(a => !a.IsDynamic)
            .SelectMany(a => a.GetTypes())
            .FirstOrDefault(t => t.FullName.Equals(fullName));
}

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.

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