Using Automapper for a project, just mapping 2 objects to each other, nothing fancy. I must have something configured incorrectly because AutoMapper keeps saying that there are UnMapped Properties.
Here's the AutoMapper config.
var mapperConfig = new MapperConfiguration(cfg => {cfg.CreateMap<SrcObj, DestObj>()
.ForMember(dest => dest.Level, opt => opt.MapFrom(src => src.lvl));}
mapperConfig.AssertConfigurationIsValid();
SrcObj
public class SrcObj
{
public int Id { get; set; }
public int ParentNode { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public bool? IsActive { get; set; }
public string AreaName { get; set; }
public int? DisplayOrder { get; set; }
public Int64 Type{ get; set; }
public int lvl { get; set; }
}
DestObj
public class DestObj
{
public int Id { get; set; }
public int ParentNode { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public bool? IsActive { get; set; }
public string AreaName { get; set; }
public int? DisplayOrder { get; set; }
public Int64 Type{ get; set; }
public int Level { get; set; }
}
And the Implementation:
var items = await _context.Database.SqlQuery<SrcObj>($"EXEC spGenerateMenu {app1}").ToListAsync();
var rslt = _mapper.Map<DestObj>(items);
and the error:
{"\nUnmapped members were found. Review the types and members below.\nAdd a custom mapping expressio...}
The error actually lists every member of the DestObj. Not sure what I'm missing. probably something simple
Because your source is a List, you need to map it also to a List:
var rslt = _mapper.Map<List<DestObj>>(items);
Related
In the data access level, I have defined such an entity:
public class Instagram
{
public int Id { get; set; }
public string Username { get; set; } = null!;
public string Password { get; set; } = null!;
public string? StateData { get; set; }
public string? TwoFactorLoginInfo { get; set; }
public string? ChallengeLoginInfo { get; set; }
public bool IsActive { get; set; }
public bool IsSelected { get; set; }
public long UserId { get; set; }
public User User { get; set; } = null!;
public Proxy? Proxy { get; set; }
public int? ProxyId { get; set; }
public List<Work>? Works { get; set; }
}
At the abstraction level, there is such a DTO:
public class InstagramDto
{
public int Id { get; set; }
public string Username { get; set; } = null!;
public string Password { get; set; } = null!;
public string? StateData { get; set; }
public string? TwoFactorLoginInfo { get; set; }
public string? ChallengeLoginInfo { get; set; }
public bool IsSelected { get; set; }
public bool IsActive { get; set; }
public UserDto? User { get; set; }
public ProxyDto? Proxy { get; set; }
}
Did I form the DTO correctly? It maps well to one side (from EF to DTO), but the problem is reverse mapping. I do it like this:
CreateMap<InstagramDto, Instagram>()
.ForMember(x => x.UserId,
expression => expression.MapFrom((dto, _) => dto.User?.Id))
.ForMember(x => x.User, expression => expression.Ignore())
.ForMember(x => x.Proxy,
expression => expression.MapFrom((dto, _) => dto.Proxy?.Id))
.ForMember(x => x.Proxy, expression => expression.Ignore());
CreateMap<Instagram, InstagramDto>();
That is, InstagramDto must have UserDTO and ProxyDto so that I can correctly map the entity from DTO to ef. At the same time, the user may have some other navigation properties that are not involved when receiving Instagram. This means that I cannot update the User, as its navigation properties are not loaded in this situation. Is this the right approach or would it be better to do so:
public int Id { get; set; }
public string Username { get; set; } = null!;
public string Password { get; set; } = null!;
public string? StateData { get; set; }
public string? TwoFactorLoginInfo { get; set; }
public string? ChallengeLoginInfo { get; set; }
public bool IsSelected { get; set; }
public bool IsActive { get; set; }
public long UserId { get; set; }
public int ProxyId { get; set; }
I have many to many relationship tables such as "User & Notification & UserNotification" and their entities, view models also.
There is only a difference between ViewModel and Entity classes. HasRead property is inside NotificationViewModel. How Can I map this entities to view models? I could not achieve this for HasRead property.
What I did so far is,
Mapping Configuration:
CreateMap<Notification, NotificationViewModel>();
CreateMap<User, UserViewModel>().ForMember(dest => dest.Notifications, map => map.MapFrom(src => src.UserNotification.Select(x => x.Notification)));
Notification class:
public class Notification : IEntityBase
{
public Notification()
{
this.UserNotification = new HashSet<UserNotification>();
}
public int Id { get; set; }
public string Header { get; set; }
public string Content { get; set; }
public System.DateTime CreateTime { get; set; }
public bool Status { get; set; }
public virtual ICollection<UserNotification> UserNotification { get; set; }
}
User Class
public class User : IEntityBase
{
public User()
{
this.UserNotification = new HashSet<UserNotification>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public bool Status { get; set; }
public virtual ICollection<UserNotification> UserNotification { get; set; }
}
UserNotification class:
public class UserNotification : IEntityBase
{
public int Id { get; set; }
public int UserId { get; set; }
public int NotificationId { get; set; }
public bool HasRead { get; set; }
public virtual Notification Notification { get; set; }
public virtual User User { get; set; }
}
UserViewModel class
public class UserViewModel : IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public bool Status { get; set; }
public IList<NotificationViewModel> Notifications { get; set; }
}
NotificationViewModel class
public class NotificationViewModel
{
public int Id { get; set; }
public string Header { get; set; }
public string Content { get; set; }
public System.DateTime CreateTime { get; set; }
public bool Status { get; set; }
public bool HasRead { get; set; } // this is the difference
}
In order to fix up the HasRead, maybe you can utilize the AfterMap(Action<TSource, TDestination> afterFunction) function. It's not as elegant as the rest of automapper, but it might work.
CreateMap<User, UserViewModel>()
.ForMember(dest => dest.Notifications, map => map.MapFrom(src => src.UserNotification.Select(x => x.Notification)))
.AfterMap((src, dest) =>
{
foreach (var notificationVM in dest.Notifications)
{
notificationVM.HasRead = src.UserNotification.Where(x => x.NotificationId == notificationVM.Id).Select(x => x.HasRead).FirstOrDefault();
}
});
In my import function, i am replacing existing documents or adding new ones using the Upsert option:
var builder = Builders<FacilityDocument>.Filter;
var filter = builder.Eq(x => x.Language.LCID, lcid)
& builder.Eq(x => x.Name, facility.Name)
& builder.Eq(x => x.NameDetailed, facility.NameDetailed)
& builder.Gte(x => x.ImportedDate, new DateTime(DateTime.Now.Year, 1, 1));
collection.ReplaceOne(filter, facility, new UpdateOptions { IsUpsert = upsert });
Now in my POCO class, i have it configured to use GUID instead of an ObjectID, like this:
[BsonId]
[BsonIgnoreIfDefault]
public Guid ID { get; set; }
The problem is that in the database, instead of generating a GUID, its defaulting back to ObjectId:
And what it should be doing, is this (which works when using the regular Insert method):
Much appreciated if anyone have a solution for this.
Update
This is my entire facilitydocument class:
[BsonId]
[BsonIgnoreIfDefault]
public Guid ID { get; set; }
public string Name { get; set; }
public string NameDetailed { get; set; }
public CommuneDocument Commune { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Homepage { get; set; }
public FacilityTypeDocument FacilityType { get; set; }
public FacilityPlacement FacilityPlacement { get; set; }
public int CoursesCount { get; set; }
public CoursesData[] CoursesData { get; set; }
public OwnershipDocument Ownership { get; set; }
public OperationDocument Operation { get; set; }
public string ExternalRemarks { get; set; }
public GisLocationData GisLocationData { get; set; }
public string ContactPersonName { get; set; }
public string ContactPersonEmail { get; set; }
public string InternalRemarks { get; set; }
public bool Active { get; set; }
public LanguageDocument Language { get; set; }
public DateTime ImportedDate { get; set; }
public string ImportedBy { get; set; }
public string UpdatedBy { get; set; }
public DateTime UpdatedDate { get; set; }
public List<ChangeLog> ChangeLog { get; set; }
Update 2
If i set my ID before the replace method, i get an error like this:
A write operation resulted in an error. The _id field cannot be changed from {_id: BinData(3, BF515DEF5743F547BD3EABB1A89DAC4D)} to {_id: BinData(3, 6364DF16640A4346B62E6B866BF76069)}
This is how i set it:
facilityDocument.ID = Guid.NewGuid();
I am using automapper for mapping view models and entity models with each other, all was good, but now i have a little different scenario where AutoMapper is not able to map my types.
My View Model:
public class CriminalSearchViewModel
{
public CriminalSearchParamsViewModel SearchParameters { get; set; }
public SelectList GenderSelectList { get; set; }
public SelectList NationalitySelectList { get; set; }
public SelectList CrimeSelectList { get; set; }
public SelectList CriminalStatusSelectList { get; set; }
}
second view model:
public class CriminalSearchParamsViewModel
{
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public int? GenderID { get; set; }
public int? StatusID { get; set; }
public string CNIC { get; set; }
public int? AgeFrom { get; set; }
public int? AgeTo { get; set; }
public double? Height { get; set; }
public int Weight { get; set; }
public int? NationalityID { get; set; }
}
and my Business Model:
public class CriminalSearch
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int? GenderID { get; set; }
public int? StatusID { get; set; }
public string CNIC { get; set; }
public int? AgeFrom { get; set; }
public int? AgeTo { get; set; }
public double? Height { get; set; }
public int Weight { get; set; }
public int? NationalityID { get; set; }
}
I have defined mapping like:
Mapper.CreateMap<CriminalSearch, CriminalSearchParamsViewModel>();
also tried this as well:
Mapper.CreateMap<CriminalSearchParamsViewModel,CriminalSearchViewModel>()
.ForMember(dest => dest.SearchParameters, opt =>
opt.MapFrom(src => Mapper.Map<CriminalSearchParamsViewModel, CriminalSearch>(src)));
and in controller i am trying like:
public ActionResult Search(CriminalSearchViewModel searchVM)
{
if (ModelState.IsValid)
{
var searchParams = searchVM.SearchParameters;
var criminalSearch = AutoMapper.Mapper.Map<CriminalSearch>(searchParams);
_criminalService.SearchCriminals(criminalSearch);
}
return View();
}
But it always throws exception:
Missing type map configuration or unsupported mapping.
Mapping types:
CriminalSearchParamsViewModel -> CriminalSearch
NationalCriminals.UI.ViewModels.CriminalSearchParamsViewModel -> NationalCriminals.Core.Models.CriminalSearch
Destination path:
CriminalSearch
Source value:
NationalCriminals.UI.ViewModels.CriminalSearchParamsViewModel
Anybody can pint me what is going wrong?
You just need to change the order of the generic args in the method CreateMap:
Mapper.CreateMap<CriminalSearchParamsViewModel,CriminalSearch>()
Thats because the first generic arg is the Source type and the second is the Destination, it is not two way, you must to declare the both if you want to map from a type to another and viceversa like this:
Mapper.CreateMap<CriminalSearchParamsViewModel,CriminalSearch>()
Mapper.CreateMap<CriminalSearch,CriminalSearchParamsViewModel>()
The method CreateMap is described like this:
AutoMapper.Mapper.CreateMap<SourceClass, DestinationClass>();
Suggest: Using AutoMapper: Creating Mappings
I am trying to use AutoMapper to map a ViewModel to a Model.
Here is my simplified ViewModel (the source) class:
public class EditPaypointVM
{
public Int64 Id { get; set; }
public Int64 OrganisationId { get; set; }
[Required]
public string OrganisationContactNumber { get; set; }
public Int64 PostalAddressId { get; set; }
public string PostalAddressAddressText { get; set; }
[Required]
public Int64 PostalAddressArea { get; set; }
public string PostalAddressAreaText { get; set; }
public string PostalAddressCode { get; set; }
public Int64 PhysicalAddressId { get; set; }
public string PhysicalAddressAddressText { get; set; }
[Required]
public Int64 PhysicalAddressArea { get; set; }
public string PhysicalAddressAreaText { get; set; }
public string PhysicalAddressCode { get; set; }
}
Here is my simplified Model (destination) class:
public class Paypoint
{
public Int64 Id { get; set; }
public virtual Organisation Organisation { get; set; }
public virtual Employer Employer { get; set; }
public virtual List<EmploymentContract> EmploymentContracts { get; set; }
public bool IsActive { get; set; }
}
public class Organisation
{
public Int64 Id { get; set; }
public virtual List<EmailAddress> EmailAdresses { get; set; }
public virtual List<ContactNumber> ContactNumbers { get; set; }
public virtual List<Address> Adresses { get; set; }
public string RegisteredName { get; set; }
public string TradingName { get; set; }
public string RegistrationNumber { get; set; }
public string WebsiteAddress { get; set; }
}
Here is the code I execute to create mappings in memory on application start:
Mapper.CreateMap<EditPaypointVM, Paypoint>()
.ForMember(dest => dest.IsActive,
opt => opt.UseValue(true))
.ForMember(dest => dest.Organisation,
opt => opt.UseDestinationValue())
.Ignore(i => i.Employer)
.Ignore(i => i.EmploymentContracts);
Upon executing 'AssertConfigurationIsvalid' within a unit test, an "Unmapped error is thrown which states that the Organisation member of Paypoint is unmapped.
Any ideas on what causes this?