Using the following entities
public class User
{
public Guid Id { get; set; }
public string Username { get; set; }
}
public class GeneralEntity
{
public Guid Id { get; set; }
public User CreatedByUser { get; set; }
public User DeletedByUser { get; set; }
}
How do I flatten this to the GeneralEntityDto below?
public class GeneralEntityDto
{
public Guid Id { get; set; }
public string CreatedByUsername { get; set; }
public string DeletedByUsername { get; set; }
}
I have tried setting up my mappings as seen below but it fails with a complaint about "CreatedByUsername" and "DeletedByUsername" not being mapped.
protected void Configure()
{
CreateMap<GeneralEntity, GeneralEntityDto>()
.ForMember(dest => dest.CreatedByUsername,
opt => opt.MapFrom(src => src.CreatedByUser.Username))
.ForMember(dest => dest.DeletedByUsername, opt =>
opt.MapFrom(src => src.DeletedByUser.Username));
}
You can use the naming convention that automapper provides.
Basically if you include the exact string of the property name of the source Object you do not have to add ForMember() automapper is clever enough to do it automatically.
That means for example :
public class GeneralEntity
{
public Guid Id { get; set; }
public User CreatedBy { get; set; } // renaming just for simplicity
public User DeletedBy { get; set; } // renaming just for simplicity
}
public class GeneralEntityDto
{
public Guid Id { get; set; }
public string CreatedByUsername { get; set; }
public string DeletedByUsername { get; set; }
}
Reference also to these:
http://docs.automapper.org/en/stable/Flattening.html
AutoMapper TwoWay Mapping with same Property Name
Related
Hi I have a question about automapper, thing is I have a model that has nested collection of other models, and models in that collection also has a collection of models something like (DB model):
public class Cabin
{
public uint Id { get; set; }
public string Name { get; set; }
public Rack[] Racks { get; set; }
}
public class Rack
{
public uint Id { get; set; }
public string RackName { get; set; }
public IPAddress IpAddress { get; set; }
public int Port { get; set; }
public Module[] Modules { get; set; }
}
public class Module
{
public uint Id { get; set; }
public string ModuleName { get; set; }
}
Well from Dto side I have something like:
public class CabinDto
{
public uint Id { get; set; }
public string Name { get; set; }
public RackDto[] Racks { get; set; }
}
public class RackDto
{
public uint Id { get; set; }
public string Name { get; set; }
public ModuleDto[] Modules{ get; set; }
}
public class ModuleDto
{
public string Name { get; set; }
}
So I want to map it all at once, but figure out a way to map a list object with different properties names.
For main class I have:
CreateMap<Db.Cabin, Dto.Cabin>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name));
// how to map nested list
I could just add some method that assigns values and map to this method, but it does not feel right. I looked in documentation and there are only examples with simple collection with same name lists.
Is there a way to do it?
You just need to add mapping for the type in the nested list and AutoMapper will take care of it.
CreateMap<Db.Module, Dto.Module>();
CreateMap<Db.Rack, Dto.Rack>();
Also when the name of properties in source and origin are the same, you don't need to call the ForMember() method.
So in your case you need it for the ModuleName to Name of the Module to ModuleDto mapping, and same for the Rack class, see this fiddle.
I have the following classes (One-One relationship Asset-TrackingDevice):
public class Asset
{
public int Id { get; set; }
public string Name { get; set; }
public TrackingDevice TrackingDevice { get; set; }
}
public class TrackingDevice
{
public int Id { get; set; }
public string Imei { get; set; }
public int? AssetId { get; set; }
public Asset Asset { get; set; }
}
The viewModels are very similar:
public class AssetViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int? TrackingDeviceId { get; set; }
public TrackingDeviceViewModel TrackingDevice { get; set; }
}
public class TrackingDeviceViewModel
{
public int Id { get; set; }
public string Imei { get; set; }
public AssetViewModel Asset { get; set; }
public string AssetId { get; set; }
}
Mappings:
CreateMap<Asset, AssetViewModel>()
.ForMember(d => d.TrackingDevice, map => map.Ignore());
CreateMap<AssetViewModel, Asset>()
.ForMember(d => d.TrackingDevice, map => map.Ignore());
CreateMap<AssetViewModel, Asset>()
.ReverseMap();
CreateMap<TrackingDevice, TrackingDeviceViewModel>()
.ForMember(d => d.Asset, map => map.Ignore());
CreateMap<TrackingDeviceViewModel, TrackingDevice>()
.ForMember(d => d.Asset, map => map.Ignore());
CreateMap<TrackingDevice, TrackingDeviceViewModel>()
.ReverseMap();
When I perform a database query to obtain the TrackingDevices,
I get an error because in the mapping the Asset within Tracking Device also includes a Tracking Device and so on.
The query that I execute to obtain the tracking devices is:
var trackingDevices = _appContext.TrackingDevices
.Include(td => td.Asset)
.ToListAsync();
var trackingMapper = Mapper.Map<IEnumerable<TrackingDeviceViewModel>>(trackingDevices);
I read that by including the Map.Ignore would fix the problem but it did not work either, does anyone know what my error is?
I have two class TenantRestrictSourceEntity, TenantRestrictSource and mapper profile
CreateMap<TenantRestrictSourceEntity, TenantRestrictSource>()
.ForMember(dest => dest.Tenant, opt => opt.Ignore());
public class TenantRestrictSourceEntity
{
public string SourceType { get; set; }
public bool? Enable { get; set; }
public int TenantId { get; set; }
}
public sealed class TenantRestrictSource
{
public int Id { get; set; }
public string SourceType { get; set; }
public bool Enable { get; set; }
public int TenantId { get; set; }
public Tenant Tenant { get; set; }
}
When I map one TenantRestrictSourceEntity to one TenantRestrictSource with Mapper.Map(tenantRestrictSourceEntity, tenantRestrictSource). Everything works fine. Tenant property was ignored correctly.
But when I try to map a list TenantRestrictSourceEntity to a list TenantRestrictSource with Mapper.Map(tenantRestrictSourceEntities, tenantRestrictSources) Tenant property is always null.
How can I ignore that property when mapping a list object?
I've tried numerous examples on here and from the automapper wiki and I am still unable to get this issue resolved. I am trying to map a nested object and a nested collection and no matter what I do it always throws an error. The only way I can get the controller to return data is by turning on option.ignore for the two properties.
These are the business layer objects I am trying to map
public class LocationBL
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string Country { get; set; }
public DbGeography Coordinates { get; set; }
public int LocationType_Id { get; set; }
public virtual LocationTypeBL LocationType { get; set; }
public virtual ICollection<SportBL> Sports { get; set; }
}
public class LocationTypeBL
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<LocationBL> Locations { get; set; }
}
public class SportBL
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<LocationBL> Locations { get; set; }
public virtual ICollection<UserBL> Users { get; set; }
}
These are the data layer objects
public class Location : EntityData
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("Company")]
public int? CompanyId { get; set; }
[Required]
public string Name { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string Country { get; set; }
[Required]
public DbGeography Coordinates { get; set; }
[ForeignKey("LocationType")]
public int LocationType_Id { get; set; }
public virtual LocationType LocationType { get; set; }
public virtual ICollection<Sport> Sports { get; set; }
public virtual Company Company { get; set; }
}
public class LocationType : EntityData
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
public class Sport : EntityData
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Location> Locations { get; set; }
public virtual ICollection<User> Users { get; set; }
}
This is my mapping profile
public class LocationProfile : Profile
{
public LocationProfile()
{
CreateMap<LocationType, LocationTypeBL>();
CreateMap<LocationTypeBL, LocationType>();
CreateMap<Location, LocationBL>()
.ForMember(Dest => Dest.Sports,
opt => opt.MapFrom(src => src.Sports))
.ForMember(Dest => Dest.LocationType,
opt => opt.MapFrom(src => src.LocationType));
CreateMap<LocationBL, Location>()
.ForMember(Dest => Dest.Sports,
opt => opt.MapFrom(src => src.Sports))
.ForMember(Dest => Dest.LocationType,
opt => opt.MapFrom(src => src.LocationType));
}
}
UPDATE *******
This is my LocationType profile
public class LocationTypeProfile : Profile
{
public LocationTypeProfile()
{
CreateMap<LocationType, LocationTypeBL>();
CreateMap<LocationTypeBL, LocationType>();
}
}
This is my Sport profile
public class SportProfile : Profile
{
public SportProfile()
{
CreateMap<Sport, SportBL>();
CreateMap<SportBL, Sport>();
}
}
Not sure if it matters but this is an Azure Mobile App backend using Autofac, WebAPI, and OWIN. This is my first time using AutoMapper and Autofac so please forgive me as I am still learning. The profiles are all registered and if I set the nested objects to ignore, the controller returns the proper data.
Thank you in advance!!!
You are almost there. You need to instruct AutoMapper on how to map the nested objects as well. So you need to create a map for the Sport to SportBL, and vice-versa, also.
// use ForMember if needed, but you know how to do that so I won't
// show it.
CreateMap<Sport, SportBL>();
Then AutoMapper will use that mapping when it mapping nested complex types.
Another note, if your classes have the same properties, you can just call the ReverseMap() method and it will do bidirectional mapping for you.
So instead of this:
CreateMap<LocationType, LocationTypeBL>();
CreateMap<LocationTypeBL, LocationType>();
You can just do this to accomplish the same thing:
Mapper.CreateMap<LocationType, LocationTypeBL>().ReverseMap();
I have a class, like so
public MyObject {
public long Id { get; set; }
public string Name {get; set; }
}
I would like to setup a link between this class and another object of the same type. So i need another object to handle the many-to-many relationship, which is fine, something like this
public MyRelationship {
public long Id { get; set; }
public string Name { get; set; }
}
But how do i configure the rest. I have tried examples online, but they are too different objects.
I have tried adding to navigation properties to MyRelationship for the link, like so
public MyRelationship {
public long Id { get; set; }
public string Name { get; set; }
public MyObject Parent { get; set; }
public MyObject Child { get; set; }
}
And also 2 collections to MyObject, like so
public MyObject {
public long Id { get; set; }
public string Name {get; set; }
public virtual ICollection<MyRelationship> ParentRelationships { get; set; }
public virtual ICollection<MyRelationship> ChildRelationships { get; set; }
}
Then in my configuration file i have added
// relationships
this.HasMany(e => e.ParentRelationships)
.WithRequired(e => e.Parent)
.HasForeignKey(e => e.ParentId)
.WillCascadeOnDelete(false);
this.HasMany(e => e.ChildRelationships)
.WithRequired(e => e.Child)
.HasForeignKey(e => e.ChildId)
.WillCascadeOnDelete(false);
But i get errors, like this
he navigation property 'ChildRelationships' declared on type 'MyObject' has been configured with conflicting foreign keys.
Why don't you just do this?
public MyObject{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<MyObject> Parents { get; set; }
public ICollection<MyObject> Children { get; set; }
}