How to ignore an inner nested object when using AutoMapper - c#

Hello I have the classes:
Class User
public class User
{
public Int64 Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public Profile Profile { get; set; } //EF one to one
}
Class Profile
public class Profile
{
public Int64 Id { get; set; }
public string Skype { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual User User { get; set; } //This is because EF Mappings
}
Class User DTO
public class UserDTO
{
public string Name { get; set; }
public string Email { get; set; }
public Profile Profile { get; set; }
}
I did the configurations to Map User to UserDTO
Mapper.CreateMap<User, UserDTO>();
I need to have the Profile.User because of the Entity Framework One to One Relationship but I don't want the Profile.User to be shown in the Mapping.
How can I ignore the Profile.User?

You could use a UserProfileDTO class that omits User
public class UserProfileDTO
{
public string Skype { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public ICollection<AddressDTO> Addresses { get; set; }
}
public class UserDTO
{
public string Name { get; set; }
public string Email { get; set; }
public UserProfileDTO Profile { get; set; }
}
Mapper.CreateMap<User, UserDTO>();
Mapper.CreateMap<Profile, UserProfileDTO>();

Related

Auto mapper makes error when mapping class with another class properties

I have following two class structures, its CASADetialsResponse as follows,
public class CASADetialsResponse
{
public string status { get; set; }
public string message { get; set; }
public List<object> validation { get; set; }
public Data data { get; set; }
}
public class LinkedCard
{
public string cardNumber { get; set; }
}
public class JointParty
{
public string jointName { get; set; }
}
public class Account
{
public string accountNumber { get; set; }
public string accountNickName { get; set; }
public List<LinkedCard> linkedCards { get; set; }
public List<JointParty> jointParty { get; set; }
public List<object> productValidation { get; set; }
}
public class Transaction
{
public string accountNumber { get; set; }
public string valueDate { get; set; }
public string transactionDetails { get; set; }
public string postDate { get; set; }
}
public class Data
{
public Account account { get; set; }
public List<Transaction> transactions { get; set; }
}
And the CASADetails class structure as follows,
public class CASADetails
{
public string status { get; set; }
public string message { get; set; }
public List<object> validation { get; set; }
public Data data { get; set; }
}
public class LinkedCard
{
public string cardNumber { get; set; }
}
public class JointParty
{
public string jointName { get; set; }
}
public class Account
{
public string accountNumber { get; set; }
public string accountNickName { get; set; }
public List<LinkedCard> linkedCards { get; set; }
public List<JointParty> jointParty { get; set; }
public List<object> productValidation { get; set; }
}
public class Transaction
{
public string accountNumber { get; set; }
public string valueDate { get; set; }
public string transactionDetails { get; set; }
public string postDate { get; set; }
}
public class Data
{
public Account account { get; set; }
public List<Transaction> transactions { get; set; }
}
When I use _mapper.Map<CASADetialsResponse>(casaResponse); I'm getting this error:
Error mapping types:
Mapping types:
CASADetails -> CASADetialsResponse
AccountManagement.Domain.CASADetails -> AccountManagement.Application.Dtos.CASADetails.CASADetialsResponse
Type Map configuration:
CASADetails -> CASADetialsResponse
AccountManagement.Domain.CASADetails -> AccountManagement.Application.Dtos.CASADetails.CASADetialsResponse
Destination Member:
data
This is how I map the two classes,
public class CASADetailsProfile : Profile
{
public CASADetailsProfile()
{
// Source -> Target
CreateMap<CASADetialsRequest, CASADetails>();
CreateMap<CASADetails, CASADetialsResponse>();
}
}
I just commented the public Data data { get; set; } from the both classes, and without any error its worked. I think problem is with that line. may I know the reason? please help me
The namespace for Data class is different, even though their content is the same.
Delete these
and refer to source Data class namespace or
If you don't want to delete them, add the following configuration
public class CASADetailsProfile: Profile
{
public CASADetailsProfile()
{
// Source -> Target
CreateMap<CASADetialsRequest, CASADetails>();
CreateMap<CASADetails, CASADetialsResponse>();
CreateMap<Sources.Data, Destinations.Data>();
CreateMap<Sources.Account, Destinations.Account>();
CreateMap<Sources.Transaction, Destinations.Transaction>();
CreateMap<Sources.LinkedCard, Destinations.LinkedCard>();
CreateMap<Sources.JointParty, Destinations.JointParty>();
}
}
Change Sources namespace and Destinations namespace to the namespace that you have

EF core 2.0, OwnsOne in TPH model classes

I have problem when I try to migrate my model in EF Core 2.0.
public class Profile
{
[Key]
public Guid Id { get; set; }
public Guid UserId { get; set; }
public ExternalUser User { get; set; }
}
public class OrganizationCustomerProfile : Profile
{
public string CompanyName { get; set; }
public Address LegalAddress { get; set; }
public Address ActualAddress { get; set; }
public BusinessRequisites Requisites { get; set; }
public string President { get; set; }
public IEnumerable<ContactPerson> ContactPerson { get; set; }
}
public class PersonCustomerProfile : Profile
{
public FullName Person { get; set; }
public Address Address { get; set; }
public string PhoneNumber { get; set; }
}
public class ContactPerson
{
[Key]
public Guid Id { get; set; }
public FullName Person { get; set; }
public string Rank { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public Guid ProfileId { get; set; }
public Profile Profile { get; set; }
}
Here I want to add complex datatypes Address and BusinessRequisites, which are:
public class BusinessRequisites
{
public string OGRN { get; set; }
public string INN { get; set; }
public string KPPCode { get; set; }
public string SettlementAccount { get; set; }
public string RCBIC { get; set; }
public string CorrespondentAccount { get; set; }
public string BankName { get; set; }
}
public class Address
{
public string FullAddress { get; set; }
public float Latitude { get; set; }
public float Longtitude { get; set; }
}
Code which I use for TPH binding:
public DbSet<Profile> UserProfiles { get; set; }
public DbSet<ContactPerson> ContactPerson { get; set; }
public DbSet<OrganizationCustomerProfile> OrganizationCustomerProfile { get; set; }
...
modelBuilder.Entity<Profile>().HasKey(u => u.Id);
modelBuilder.Entity<OrganizationCustomerProfile>().OwnsOne(e => e.ActualAddress);
modelBuilder.Entity<OrganizationCustomerProfile>().OwnsOne(e => e.LegalAddress);
modelBuilder.Entity<OrganizationCustomerProfile>().OwnsOne(e => e.Requisites);
But when I try to make a migration, I get an error:
"Cannot use table 'UserProfiles' for entity type
'OrganizationCustomerProfile.ActualAddress#Address' since it has a
relationship to a derived entity type 'OrganizationCustomerProfile'.
Either point the relationship to the base type 'Profile' or map
'OrganizationCustomerProfile.ActualAddress#Address' to a different
table."
So, what the reason of this error? Is it not possible to create hierarchy inheritance in EF Core 2.0?
Thank you!
It seems like this isn't supported at the moment:
https://github.com/aspnet/EntityFrameworkCore/issues/9888

Unable to save data using entity frame work code first technique

I am unable to save data using code first technique.
here is my context:
public virtual DbSet<Users> User { get; set; }
public virtual DbSet<Agency> Agencies { get; set; }
public virtual DbSet<ColdStorage> ColdStorages { get; set; }
public virtual DbSet<ShowRoom> ShowRooms { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
and my user model is here:
[Table("Users")]
public class Users
{
[Key]
public int UserId { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool isAgency { get; set; }
public bool isColdStorage { get; set; }
public string VerificationCode { get; set; }
public DateTime CreatedDate { get; set; }
// Reverse navigation
public virtual Agency Agency { get; set; }
public virtual ColdStorage ColdStorage { get; set; }
public virtual ShowRoom ShowRoom { get; set; }
public Users()
{
Agency = new Agency();
ColdStorage = new ColdStorage();
ShowRoom = new ShowRoom();
}
}
and my other model is here:
[Table("Agency")]
public class Agency
{
[Key]
public int AgencyId { get; set; }
[ForeignKey("Users")]
public int UserId { get; set; }
public string AgencyName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
[Required]
public virtual Users Users { get; set; }//Foriegn key
}
And the error is here:
Message":"An error has occurred.","ExceptionMessage":"One or more validation errors were detected during model generation:\r\n\r\nColdStorage_Users_Source: : Multiplicity is not valid in Role 'ColdStorage_Users_Source' in relationship 'ColdStorage_Users'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.\r\nShowRoom_Users_Source:
Just like the error says.
"because the Dependent Role properties are not the key properties, the
upper bound of the multiplicity of the Dependent Role must be '*'"
The "Dependent Role properties" here means, eg Agency.UserId, and the "multiplicity must be '*'" means Users must have a collection of Agencies. EG
public virtual ICollection<Agency> Agencies { get; } = new HashSet<Agency>();

EntityFramework code first keys

I have following tables: User, UserGroups, and UserInGroups. You can see them on picture below. When i call User i want to be able to get Groups that user is in (UserInGroups). I am reading materials about EntityFramework but i am unable to make connections in code to to that, what am i missing? Do i need to connect them onModelCreating?
Currently i am not getting any data from UserInGroup or UserGroups.
DB looks like this
My classes look like this:
public class User : BaseEntity
{
public int RoleId { get; set; }
public Role Role { get; set; }
public UserGroup UserGroup { get; set; }
public UserInGroup UserInGroup { get; set; }
}
public class UserGroup : BaseEntity
{
public UserGroup()
{
Users = new List<User>();
UserInGroups = new List<UserInGroup>();
}
[StringLength(255)]
public string Name { get; set; }
public string KeyName { get; set; }
public List<User> Users { get; set; }
public List<UserInGroup> UserInGroups { get; set; }
}
public class UserInGroup : BaseEntity
{
public UserInGroup()
{
Users = new List<User>();
UserGroups = new List<UserGroup>();
}
public int UserId { get; set; }
public User User { get; set; }
public int UserGroupId { get; set; }
public UserGroup UserGroup { get; set; }
public List<User> Users { get; set; }
public List<UserGroup> UserGroups { get; set; }
}
DbContext:
public DbSet<GlobalSettings> GlobalSettings { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserGroup> UserGroups { get; set; }
public DbSet<UserInGroup> UsersInGroups { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<GlobalSettings>().Property(x => x.Key).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index_VariablenName") { IsClustered = false, IsUnique = true } }));
}
public abstract partial class BaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
public class User : BaseEntity
{
public string Username { get; set; }
public string Title { get; set; }
public FirstName { get; set; }
public string LasName { get; set; }
public Genders Gender { get; set; }
public string Email { get; set; }
public int RoleId { get; set; }
public string TechUser { get; set; }
public DateTime TechChangeDate { get; set; }
public int TechVersion { get; set; }
public bool IsDeleted { get; set; }
public virtual Role Role { get; set; }
public virtual ICollection<UserInGroup> UserInGroups { get; set; }
}
public class UserInGroup : BaseEntity
{
public int UserId { get; set; }
public int UserGroupId { get; set; }
public string TechUser { get; set; }
public DateTime TechChangeDate { get; set; }
public int TechVersion { get; set; }
public bool IsDeleted { get; set; }
public virtual User User { get; set; }
public virtual UserGroup UserGroup { get; set; }
}
public class UserGroup : BaseEntity
{
public string Name { get; set; }
public string KeyName { get; set; }
public string TechUser { get; set; }
public DateTime TechChangeDate { get; set; }
public int TechVersion { get; set; }
public bool IsDeleted { get; set; }
}
public class Role : BaseEntity
{
public string Name { get; set; }
}
public enum Genders
{
Male = 1,
Female = 2
}
You can use two methods to fill navigation properties. First is lazy-loading and second is explicit specifying of required properties.
For lazy-loading you should declare your navigation properties as virtual:
public class User : BaseEntity
{
public int RoleId { get; set; }
public virtual Role Role { get; set; }
public virtual UserGroup UserGroup { get; set; }
public virtual UserInGroup UserInGroup { get; set; }
}
public class UserGroup : BaseEntity
{
public UserGroup()
{
Users = new HashSet<User>(); // HashSet is more effective than List
UserInGroups = new HashSet<UserInGroup>();
}
[StringLength(255)]
public string Name { get; set; }
public string KeyName { get; set; }
public virtual ICollection<User> Users { get; set; } // ICollection is less restrective
public virtual ICollection<UserInGroup> UserInGroups { get; set; }
}
Now, you can load f.e. single user:
var justUser = dbContext.Users.Single(u => u.Id == 100);
When you need its properties they will by transparently loaded:
foreach (var userInGroup in user.UsersInGroups) // here is second loading
{
. . .
}
The second way is the calling of the Include method to explicit specifying required properties:
var userWithGroups = dbContext.Users
.Include(u => u.UserInGroups) // include single navigation property
.Include(ugs => ugs.Groups.Select(ug => ug.Group)) // include collection navigation property
.Single(u => u.Id == 100); // get the user with specified id and filled specified properties

Mapping complex DTOs to entities with automapper

I want to map from
LDTTicketUploadDTO[] to IEnumerable<LDTTicket>
The mappings are created in this method and at the end I map the data.
public void UploadLDTTickets(LDTTicketUploadDTO[] ticketDTOs)
{
Mapper.CreateMap<LDTTicketUploadDTO, LDTTicket>();
Mapper.CreateMap<LDTTicketDTO, LDTTicket>();
Mapper.CreateMap<LDTCustomerDTO, LDTCustomer>();
Mapper.CreateMap<LDTDeviceDTO, LDTDevice>();
Mapper.CreateMap<LDTUnitDTO, LDTUnit>();
Mapper.CreateMap<LDTCommandDTO, LDTCommand>();
Mapper.CreateMap<LDTCommandParameterDTO, LDTCommandParameter>();
Mapper.CreateMap<LDTObjectDTO, LDTObject>();
Mapper.CreateMap<LDTControlFileDTO, LDTControlFile>();
Mapper.CreateMap<LDTDeviceDTO, LDTDevice>();
Mapper.CreateMap<LDTLanguageDTO, LDTLanguage>();
Mapper.CreateMap<LDTObjectBitDTO, LDTObjectBit>();
var tickets = Mapper.Map<IEnumerable<LDTTicketUploadDTO>, IEnumerable<LDTTicket>>(ticketDTOs);
// do something with tickets
}
This is how the DTO´s are structured:
public class LDTTicketUploadDTO
{
public LDTTicketDTO Ticket { get; set; }
public LDTDeviceDTO Device { get; set; }
public LDTCustomerDTO Customer { get; set; }
}
public enum TicketStatus
{
New,
InProgress,
Done
}
public class LDTTicketDTO
{
public bool UploadNeeded { get; set; }
public string TicketNumber { get; set; }
public TicketStatus Status { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string AssignedTo { get; set; }
public IEnumerable<LDTUnitDTO> Units { get; set; }
}
public class LDTUnitDTO
{
public int Id { get; set; }
public string FunctionUnit { get; set; }
public int FunctionUnitAddress { get; set; }
public string Zone { get; set; }
public int ZoneUnitAddress { get; set; }
public string Object { get; set; }
public int ObjectAddress { get; set; }
public IEnumerable<LDTCommandDTO> Commands { get; set; }
}
and more...
What works is that these properties are correctly mapped to their counterpart entities:
public LDTDeviceDTO Device { get; set; }
public LDTCustomerDTO Customer { get; set; }
What works NOT is that this property is not mapped:
public LDTTicketDTO Ticket { get; set; }
This is how the Entities are structured:
public class LDTTicket
{
[Key, Column(Order = 0)]
[Required]
public string SerialNumber { get; set; }
[Key, Column(Order = 1)]
[Required]
public string TicketNumber { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public string AssignedTo { get; set; }
public TicketStatus Status { get; set; }
public string CreatedBy { get; set; }
public bool UploadNeeded { get; set; }
public virtual LDTCustomer Customer { get; set; }
public virtual LDTDevice Device { get; set; }
public virtual ICollection<LDTUnit> Units { get; set; }
}
ONLY the Customer and Device property are mapped in the LDTTicket
What is wrong with my configuration?
It's expecting to populate a LDTTicket sub-property on the ticket, not the matching properties of the ticket itself. Create direct mappings onto the ticket from the Ticket subproperty of the source directly onto the matching properties of the destination. NOTE: You only need to define your mappings once, not per method execution. Mappings should be defined at app start up and thereafter used.
public void UploadLDTTickets(LDTTicketUploadDTO[] ticketDTOs)
{
Mapper.CreateMap<LDTTicketUploadDTO, LDTTicket>();
.ForMember(d => d.SerialNumber, m => m.MapFrom(s => s.Ticket.SerialNumber))
...
//Mapper.CreateMap<LDTTicketDTO, LDTTicket>(); You don't need this
Mapper.CreateMap<LDTCustomerDTO, LDTCustomer>();
Mapper.CreateMap<LDTDeviceDTO, LDTDevice>();
...
}

Categories