AutoMapper TwoWay Mapping with same Property Name - c#

Given these two objects
public class UserModel
{
public string Name {get;set;}
public IList<RoleModel> Roles {get;set;}
}
public class UserViewModel
{
public string Name {get;set;}
public IList<RoleViewModel> Roles {get;set;} // notice the ViewModel
}
Is this the most optimal way to do the mapping, or is AutoMapper capable of mapping Roles to Roles on its own?
App Config
Mapper.CreateMap<UserModel, UserViewModel>()
.ForMember(dest => dest.Roles, opt => opt.MapFrom(src => src.Roles));
Mapper.CreateMap<UserViewModel, UserModel>()
.ForMember(dest => dest.Roles, opt => opt.MapFrom(src => src.Roles));
Implementation
_userRepository.Create(Mapper.Map<UserModel>(someUserViewModelWithRolesAttached);

Is this the most optimal way to do the mapping, or is AutoMapper capable of mapping Roles to Roles on its own?
If the property names are identical, you should not have to manually provide a mapping:
Mapper.CreateMap<UserModel, UserViewModel>();
Mapper.CreateMap<UserViewModel, UserModel>();
Just make sure the inner types are mapped as well (RoleViewModel ↔ RoleModel)
What this means, however, is that if you change a source or destination property name, AutoMapper mappings can fail silently and cause hard to track down problems (e.g., if you changed UserModel.Roles to UserModel.RolesCollection without changing UserViewModels.Roles).
AutoMapper provides a Mapper.AssertConfigurationIsValid() method that will check all of your mappings for errors and catch misconfigured mappings. It's useful to have a unit test that runs with the build that validates your mappings for this kind of problem.

You don't need to map the properties. Just make sure that the property names match and there is a mapping defined between them.
Mapper.CreateMap<UserModel, UserViewModel>();
Mapper.CreateMap<UserViewModel, UserModel>();
Mapper.CreateMap<RoleModel, RoleViewModel>();
Mapper.CreateMap<RoleViewModel, RoleModel>();
Or with the cooler way I just found out:
Mapper.CreateMap<UserModel, UserViewModel>().ReverseMap();
Mapper.CreateMap<RoleModel, RoleViewModel>().ReverseMap();

All the other answers, are much better (which I gave an upvote to each).
But what I wanted to post here is a quick playground that you could copy and past right into LinqPad in C# program mode and play your idea's without messing with your actual code.
Another awesome thing about moving all your conversions into a TyperConverter class is that your conversions are now Unit Testable. :)
Here you will notice that the model and viewmodel are almost identical except for one property. But through this process the right property is converted to the correct property in the destination object.
Copy this code into LinqPad and you can run it with the play button after switching to C# Program mode.
void Main()
{
AutoMapper.Mapper.CreateMap<UserModel, UserViewModel>().ConvertUsing(new UserModelToUserViewModelConverter());
AutoMapper.Mapper.AssertConfigurationIsValid();
var userModel = new UserModel
{
DifferentPropertyName = "Batman",
Name = "RockStar",
Roles = new[] {new RoleModel(), new RoleModel() }
};
var userViewModel = AutoMapper.Mapper.Map<UserViewModel>(userModel);
Console.WriteLine(userViewModel.ToString());
}
// Define other methods and classes here
public class UserModel
{
public string Name {get;set;}
public IEnumerable<RoleModel> Roles { get; set; }
public string DifferentPropertyName { get; set; }
}
public class UserViewModel
{
public string Name {get;set;}
public IEnumerable<RoleModel> Roles { get; set; } // notice the ViewModel
public string Thingy { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(string.Format("Name: {0}", Name));
sb.AppendLine(string.Format("Thingy: {0}", Thingy));
sb.AppendLine(string.Format("Contains #{0} of roles", Roles.Count()));
return sb.ToString();
}
}
public class UserModelToUserViewModelConverter : TypeConverter<UserModel, UserViewModel>
{
protected override UserViewModel ConvertCore(UserModel source)
{
if(source == null)
{
return null;
}
//You can add logic here to deal with nulls, empty strings, empty objects etc
var userViewModel = new UserViewModel
{
Name = source.Name,
Roles = source.Roles,
Thingy = source.DifferentPropertyName
};
return userViewModel;
}
}
public class RoleModel
{
//no content for ease, plus this has it's own mapper in real life
}
Result from the Console.WriteLine(userViewModel.ToString());:
Name: RockStar
Thingy: Batman
Contains #2 of roles

Inside the Startup.cs in the Configure() method:
Mapper.Initialize(config => {
config.CreateMap<UserModel, UserViewModel>().ReverseMap();
// other maps you want to do.
});

Related

Unflatten by convention with automapper

In my project I'm trying to use automapper to unflatten my command objects to my domain objects by convention as much as possible.
It works when I explicitly map the two members in the mapping profile, but according to the automapper documentation I think this should also work by convention.
I created a dotnetfiddle to demonstrate the minimal case.
Related questions end up with people explicitly adding the mapping, but that kind of goes against what Automapper is built for and contradicts the documentation, no?
It doesn't work with flattening either, so the reversemap is a red herring I think.
The mapping
public class Mapping: Profile
{
public Mapping()
{
this.CreateMap<CreateSelectionCommand, Selection>();
// .ForMember(selection => selection.Name, opt => opt.MapFrom(x => x.SelectionName))
.reverseMap()
}
}
What I expect to work
[Fact]
public void ShouldMapName()
{
var cmd = new CreateSelectionCommand {SelectionName = "selectionName"};
var selection = _mapper.Map<Selection>(cmd);
Assert.Equal(cmd.SelectionName, selection.Name); <== selection.Name == ""
}
Classes for context
public class Selection
{
public string Name { get; set; }
}
public class CreateSelectionCommand
{
public string SelectionName { get; set; }
}
Did I misread the docs or am I missing something?
Flattening is about mapping nested "complex" objects to properties on "higher" level i.e. in your case if CreateSelectionCommand had property Selection of type which had Name property it would be mapped to SelectionName in destination type (see this fiddle).
You can try to use prefixes by adding:
cfg.RecognizePrefixes("Selection");
to your configuration (see this fiddle) but I doubt that it is suitable option for convention based handling.
Also it seems that you can add custom name convention using ISourceToDestinationNameMapper and AddMemberConfiguration:
class TypeNamePrefixedSourceToDestinationNameMapper : ISourceToDestinationNameMapper
{
public MemberInfo GetMatchingMemberInfo(IGetTypeInfoMembers getTypeInfoMembers, TypeDetails typeInfo,
Type destType,
Type destMemberType, string nameToSearch)
{
return getTypeInfoMembers.GetMemberInfos(typeInfo)
.FirstOrDefault(mi => mi.Name == destType.Name + nameToSearch);
}
}
var config = new MapperConfiguration(cfg =>
{
cfg.AddMemberConfiguration().AddName<TypeNamePrefixedSourceToDestinationNameMapper>();
// ...
}
At least it works in this simple case, see this fiddle.

c# automapper lookup value from source model

I have a model which has a generic properties property looking something like this:
public class GenericProperty
{
public string Name { get; set; }
public object Value { get; set; }
}
Next to that I have a object that has a list with GenericProperties like this:
public class GenericEntity
{
public string Name { get; set; }
public List<GenericProperty> Properties { get; set; }
}
Now im calling a API that deserialize the json to the model above. Next i want to use AutoMapper to construct an actual good looking model so i did the following:
Mapper.Initialize(x =>
{
x.CreateMap<GenericEntity, MyModel>()
.ForMember(d => d.ManagerId, o => o.MapFrom(s => s.Properties.Where(n => n.Name == "ManagerId" ).Select(v => v.Value)))
});
Problem is that this returns the property type and not the actual value:
System.Linq.Enumerable+WhereListIterator`1[MyProject.Models.GenericProperty]
How can i lookup the value of within the model?
By using Where you are selecting all the properties with the name ManagerId. You should instead use Single like in this unit test:
public class TestClass
{
[Test]
public void TestMapper()
{
Mapper.Initialize(x =>
{
x.CreateMap<GenericEntity, MyModel>()
.ForMember(d => d.ManagerId,
o => o.MapFrom(s => s.Properties.Single(n => n.Name == "ManagerId").Value));
});
var ge = new GenericEntity
{
Properties = new List<GenericProperty>
{
new GenericProperty {Name = "ManagerId", Value = "Great"}
}
};
var myModel = Mapper.Map<MyModel>(ge);
Assert.AreEqual("Great", myModel.ManagerId);
}
}
If you can not guarantee that there will be a property with the name ManagerId, you should use SingleOrDefault, and handle the null case.
IMHO, you should limit this kind of AutoMapper configurations to simple cases, since it quickly gets difficult to debug and maintain.
For more complex mappings like this one, I would recommend you to make an explicit mapping method instead, which you can call like an extension method. Another option worth considering if you want to use Automapper are Custom value resolvers.

How to use automapper with complex types

Within my domain model for my view I have the following object that is serving as backing fields for my properties
public class ModelProperty<T>// where t:struct
{
public T Value { get; set; }
public string Description { get; set; }
public string LabelName { get; set; }
}
The object in turn is presented as:
public partial class Incident : BaseEntityModel
{
private ModelProperty<string> typeCode = new ModelProperty<string>{Description="1-C", LabelName = "Type Code"};
private ModelProperty<string> typeText = new ModelProperty<string>{Description="1-C", LabelName = "Type Text"};
public ModelProperty<string> TypeCode { get {return typeCode;}}
public ModelProperty<string> TypeText { get {return typeText;}}
}
The business object (my source) is not as complex.
public partial class Incident : ObjectBase
{
public string TypeCode { get; set; }
public string TypeText { get; set; }
}
is it possible to map the values from the source to the target. Using Automapper I have the following mapping setup
//note SrcObj is not an object but a namespace alias since the domain and business objects are of the same name
Mapper.CreateMap<SrcObj.Incident, Incident>()
.ForMember(ui => ui.TypeText.Value,
opt => opt.MapFrom(src => src.TypeText));
But I am getting the exception Expression must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead.
I'm new to automapper but in looking at the documentation is the object I am working with too complex (based on the idea that there are really three types here and not two)?
If it is possible to handle this type of mapping how is this done?
Update
Based upon the suggestion from Jimmy I have updated my code as follows:
Mapper.CreateMap<SrcObj.Incident, Incident>();
Mapper.CreateMap<string, ModelProperty<string>>()
.ConvertUsing(src => new ModelProperty<string> { Value = src });
Mapper.AssertConfigurationIsValid();
SrcObj.Incident viewModelDto = md.GenerateMockIncident(); //populate the business object with mock data
uibase = Mapper.Map<SrcObj.Incident, Incident>(viewModelDto);
The code executes and I do not get any exceptions however the value that is being set and returned in the business object is still not getting assigned to the backing property Value it is still null.
What am I missing?
-cheers
An easier way is to create a type converter:
Mapper.CreateMap<string, ModelProperty<string>>()
.ConvertUsing(src => new ModelProperty<string> { Value = src });
Then you'll have this for every time AutoMapper sees string -> ModelProperty. You won't have to do member-specific configuration at all.
Try this.. you need to give a ModelProperty object mapping to the destination TypeText
Mapper.CreateMap<Funky.Incident, Incident>()
.ForMember(ui => ui.TypeText,
opt => opt.MapFrom(src =>
new ModelProperty<string>
{
Value = src.TypeText
}));
Do the same for the TypeCode property mapping so that all fields are mapped.
You need to account for each member mapping, only if their names are different OR if their type names are different. in this case, AutoMapper will have a hard time converting string to a Model object till you give hints.
Try mapping TypeCode as well.. And i don't know the properties of ObjectBase etc. So you need to do check if any manual mapping is needed there as well.

Decorating an enum on the EF object model with a Description attribute?

I have defined an enum in my Entity Framework 5 model, which I'm using to define the type of a field on a table, e.g.
public enum PrivacyLevel : byte {
Public = 1,
FriendsOnly = 2,
Private = 3,
}
And I have a table Publication that has a tinyint field PrivacyLevel, which I've mapped in the EF model to use the PrivacyLevel type defined above, using the method described here.
But I also want to be able to display a string description for each value of the enum. This I've done in the past for enums by decorating them with a Description attribute, e.g.
public enum PrivacyLevel : byte {
[Description("Visible to everyone")]
Public = 1,
[Description("Only friends can view")]
FriendsOnly = 2,
[Description("Only I can view")]
Private = 3,
}
I've got some code that converts enums to strings by checking if they have a Description attribute, and that works well. But here, because I had to define the enum in my model, the underlying code is auto-generated, and I don't have anywhere stable to decorate them.
Any ideas for a workaround?
Not sure if this is what you are after but from what I understand i will try to be as clear as possible, since you have a concrete database first approach, you can abstract much of your Entity models to ViewModels using a Dto Approach through AutoMapper.
Using automapper profiles you can quickly setup profiles for all sorts of environments and scenarios for flexibility and adaptability
So here is this "Enum" which is causing me a problem
here is my view model for this Enum
First here is my layout
here is a simply mapping for the Account entity to a viewmodel for Account
public class AccountProfile : Profile
{
protected override void Configure()
{
// Map from Entity object to a View Model we need or use
// AutoMapper will automatically map any names that match it's conventions, ie properties from Entity to ViewModel have exact same name properties
Mapper.CreateMap<Account, AccountViewModel>()
.ForMember(model => model.CurrentPrivacy, opt => opt.MapFrom(account => (PrivacyLevelViewModel)account.PrivacyLevel));
Mapper.CreateMap<Account, EditAccountViewModel>()
.ForMember(model => model.SelectedPrivacyLevel, opt => opt.MapFrom(account => (PrivacyLevelViewModel) account.PrivacyLevel));
// From our View Model Changes back to our entity
Mapper.CreateMap<EditAccountViewModel, Account>()
.ForMember(entity => entity.Id, opt => opt.Ignore()) // We dont change id's
.ForMember(entity => entity.PrivacyLevel, opt => opt.MapFrom(viewModel => (PrivacyLevel)viewModel.NewSelectedPrivacyLevel));
}
}
Note that this does not have to apply to MVC, this can be used in WPF or other applications not tied to the Web, but since it's a good way of explaining, it's why I used MVC for this example.
When I first get a Http Get request for my profile, I grab the entity from the database
and map anything I actually need to the view
public ActionResult Index()
{
// Retrieve account from db
var account = new Account() { Id = 1, Name = "Patrick", AboutMe = "I'm just another dude", ProfilePictureUrl = "", PrivacyLevel = PrivacyLevel.Private, Friends = new Collection<Account>() };
// ViewModel abstracts the Entities and ensures behavour that only matters to the UI
var accountViewModel = Mapper.Map<AccountViewModel>(account);
return View(accountViewModel); // strongly typed view model
}
So my profile index view can use my enum view model
Here's the output
Now when I want to change what my privacy setting is, I can create a new EditAccountViewModel which allows me to submit a new value in a dropdown
public class EditAccountViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string AboutMe { get; set; }
public int NewSelectedPrivacyLevel { get; set; }
public PrivacyLevelViewModel SelectedPrivacyLevel { get; set; }
public SelectList PrivacyLevels
{
get
{
var items = Enum.GetValues(typeof (PrivacyLevelViewModel))
.Cast<PrivacyLevelViewModel>()
.Select(viewModel => new PrivacyLevelSelectItemViewModel()
{
Text = viewModel.DescriptionAttr(),
Value = (int)viewModel,
});
//SelectPrivacyLevel was mapped by AutoMapper in the profile from
//original entity value to this viewmodel
return new SelectList(items, "Value", "Text", (int) SelectedPrivacyLevel);
}
}
}
Now once I send a post of my new changed value, the interesting part is how I modify the "real" entity from the db with the updated privacy setting
On submitting the form back to my edit action you can i get the original real db entity and then merge changes if the ViewModel state is valid
AutoMapper allows you to configure how ViewModels can be mapped to Entities,
if some properties should change, from integer entities to string values for view models,
maybe you want an enum to really be a string in the "view" and only the enum for the db,
with auto mapper it allows you to configure all these scenarious, and through convention
you dont need to configure "every single property" if your view models have the same
property names/camel case to upper case.
Lastly, before you can use these Profiles, you must load them at the application entry point, like global.asax or Main.
AutoMapper only needs to be 'configured' once to load any sort of profiles defined in the application. With some reflection you can load all Profiles in your assembly with this code:
public class AutoMapperConfig
{
public static void RegisterConfig()
{
Mapper.Initialize(config => GetConfiguration(Mapper.Configuration));
}
private static void GetConfiguration(IConfiguration configuration)
{
configuration.AllowNullDestinationValues = true;
configuration.AllowNullCollections = true;
IEnumerable<Type> profiles = Assembly.GetExecutingAssembly().GetTypes().Where(type => typeof(Profile).IsAssignableFrom(type));
foreach (var profile in profiles)
{
configuration.AddProfile(Activator.CreateInstance(profile) as Profile);
}
}
}
I call the configuration in my global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
AutoMapperConfig.RegisterConfig(); // AutoMapperConfig.cs
}
More information about how to use AutoMapper and how it can benefit you can be found
here:
AutoMapper Github
In the end I came up with a much simpler solution: I just used an extension method to get the description of the enum. That also made it a lot easier for localization, so I could use a Resource string.
public static string Description(this PrivacyLevel level) {
switch (level) {
case PrivacyLevel.Public:
return Resources.PrivacyPublic;
case PrivacyLevel.FriendsOnly:
return Resources.PrivacyFriendsOnly;
case PrivacyLevel.Private:
return Resources.PrivacyPrivate;
default:
throw new ArgumentOutOfRangeException("level");
}
}
Some other idea:
Use byte PrivacyLevelByte in your EF classes. Create additional partial class for that particular model where you define property
PrivacyLevel PrivacyLevelEnum
{
get { return (PrivacyLevel)PrivacyLevelByte; }
set { PrivacyLevelByte = (byte)value;}
}
and define PrivacyLevel enum in your code and not by EF designer.
That allows you to handle any attributes but still gives you enum properties on EF models.

Automapper nested mapping

I've read the nested mapping wiki page but it appears to not like multiple levels of nesting. I've got the following maps created and classes defined.
AutoMapper.Mapper.CreateMap<Address, AddressDTO>();
AutoMapper.Mapper.CreateMap<MatchCompanyRequest, MatchCompanyRequestDTO>();
public class MatchCompanyRequest
{
Address Address {get;set;}
}
public class MatchCompanyRequestDTO
{
public CompanyInformationDTO {get;set;}
}
public class CompanyInformationDTO {get;set;}
{
public string CompanyName {get;set;}
public AddressDTO Address {get;set;}
}
But the following code...
// works
matchCompanyRequestDTO.companyInformationDTO.Address =
AutoMapper.Mapper.Map<Address, AddressDTO>(matchCompanyRequest.Address);
// fails
matchCompanyRequestDTO =
AutoMapper.Mapper
.Map<MatchCompanyRequest, MatchCompanyRequestDTO>(matchCompanyRequest);
Does this deep nesting work and I have it configured improperly? Or is this kind of nesting not yet supported?
-- Edit
For anyone interested, I am not in control of the DTOs.
It lacks the mapping from Address to CompanyInformationDTO, as those objects are on the same nest-level.
The map is created for MatchCompanyRequest -> MatchCompanyRequestDTO, but it is unable to figure out whether it can map Address to CompanyInformationDTO.
So your MatchCompanyRequestDTO could in fact have same declaration as your CompanyInformationDTO:
public class MatchCompanyRequestDTO
{
public string CompanyName {get;set;}
public AddressDTO Address {get;set;}
}
This of course only affects you if you want to use automatic mapping. You still can configure your maps manually, but it seems like the DTOs should be fixed instead, let's try anyway:
public class CustomResolver : ValueResolver<Address, CompanyInformationDTO>
{
protected override CompanyInformationDTO ResolveCore(Address source)
{
return new CompanyInformationDTO() { Address = Mapper.Map<Address, AddressDTO>(source) };
}
}
// ...
AutoMapper.Mapper.CreateMap<MatchCompanyRequest, MatchCompanyRequestDTO>()
.ForMember(dest => dest.companyInformationDTO, opt => opt.ResolveUsing<CustomResolver>().FromMember(src => src.Address)); // here we are telling to use our custom resolver that converts Address into CompanyInformationDTO
The important thing is you define how deeper is your navigation, to previne the stackoverflow problems. Imagine this possibility:
You have 2 entities Users and Notifications in NxN model (And
you have DTOs object to represent that), when you user auto mapper
without set MaxDepth in you mapper expression, "Houston we have a
problem" :).
The code below show a workaround to resolve this for all Mappers. If you want can be defined to each mapper. Like this Question
Solution 1 (Global Definition)
public class AutoMapperConfig
{
public static void RegisterMappings()
{
Mapper.Initialize(mapperConfiguration =>
{
mapperConfiguration.AddProfile<DomainModelToYourDTOsMappingProfile>();
mapperConfiguration.AddProfile<YourDTOsToDomainModelMappingProfile>();
mapperConfiguration.AllowNullCollections = true;
mapperConfiguration.ForAllMaps(
(mapType, mapperExpression) => {
mapperExpression.MaxDepth(1);
});
}
}
Solution 2 (For each Mapper)
public class AutoMapperConfig
{
public static void RegisterMappings()
{
Mapper.CreateMap<User, DTOsModel>()
.MaxDepth(1);
}
}
Consider the following instead:
public class MatchCompanyRequest
{
Address Address {get;set;}
}
public class MatchCompanyRequestDTO
{
public string Name {get;set;}
public AddressDTO Address {get;set;}
}
public class AddressDTO
{
....
}
Your DTO objects need to have the same structure as your domain objects for the default mapping conventions to work in AutoMapper.
Look at this: https://github.com/AutoMapper/AutoMapper/wiki/Projection It will explain the Projection for you, you could customize it to work the way you have it.

Categories

Resources