1

I have Instructor and Address models that looks something like:

public class Instructor : ModelBase
{

    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public virtual Address Address { get; set; }

}

public class Address : ModelBase
{
    public string Name { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City { get; set; }
    public int? StateId { get; set; }
    [Column("StateId")]
    public virtual State State { get; set; }
    public string PostalCode { get; set; }
    public Country Country { get; set; }
}

Then, I have the following View Models for each:

public class InstructorViewModel : Instructor
{
    [Required]
    [DisplayName("First Name")]
    public new string FirstName { get; set; }

    [DisplayName("Middle Name")]
    public new string MiddleName { get; set; }

    [Required]
    [DisplayName("Last Name")]
    public new string LastName { get; set; }

    public AddressViewModel AddressViewModel { get; set; }
}

public class AddressViewModel : Address
{
    [DisplayName("Location Name")]
    public new string Name { get; set; }
    [DisplayName("Address Line 1")]
    public new string Line1 { get; set; }
    [Required]
    public new string City { get; set; }
    [Required]
    [Range(1, int.MaxValue, ErrorMessage = "Please select a state.")]
    public new int? StateId { get; set; }
    [Required]
    [DisplayName("Postal Code")]
    public new string PostalCode { get; set; }
}

I know that when saving a new instructor I can simply do something like:

 var instructor = Mapper.Map<Instructor>(instructorViewModel);
 instructor.Address = Mapper.Map<Address>(instructorViewModel.AddressViewModel);

However, I am wondering if there is a better way to utilize AutoMapper to map the AddressVM to Address model? I attempted to do the following:

c.CreateMap<Instructor, InstructorViewModel>()
 .ForMember(x => x.AddressViewModel, y => y.ResolveUsing(z => z.Address));

Which does map the AddressVM on top of the Address, but the mapped instructor model has strange properties in the Address object (view model specific properties) and results in the following error from EF:

The entity type 'AddressViewModel' was not found. Ensure that the entity type has been added to the model.

What is the cleanest way to do this? Using .Net Core MVC, EF Core

adrianbanks
  • 81,306
  • 22
  • 176
  • 206

0 Answers0