简体   繁体   中英

AutoMapper and Navigational Properties

Has anyone every come across the following situation. I have an MVC app and I am using Entity Framework. I have a foreign key that I am populating into a drop down box and when the user selects their choice and submits the form I get an error about not being able to map.

I have the following Entites:

public Class City{
 public int Id {get; set;}
 public string Name {get; set;}
}


public class Property {
 public int Id {get; set;}
 public string Description {get; set;}
 public Virtual City City {get; set;}
}

I have the following View Model

public class AddPropertyVM {

  public AddPropertyViewModel(IEnumerable<City> cities){
    _cities = cities;
  } 

  public AddPropertyViewModel(){}

  public string Description {get; set;}
  public int SelectedCityId {get; set;}
  public IEnumerable<SelectListItem> CitiesItems {
    get {
      return new SelectList(_cities, "Id", "Name");
    }
  }

  private IEnuermable<City> _cities {get; set;}
}

I have the following AutoMapper Configuration:

config.CreateMap<Property, AddPropertyViewModel>().ReverseMap();

When I try to map the VM back to the property entity like this:

var newProperty = AutoMapper.Mapper.Map<AddPropertyViewModel, Property>(property);

I get the following error:

Missing type map configuration or unsupported mapping.

Mapping types: Int32 -> City System.Int32 -> Test.Entities.City

Destination path: Property.City.City

Source value: 2

Does anyone know why this is happening? Any help / guidance would be very much appreciated.

Just so it's clear. I am trying to get City back from SelectedCityId.

I've tried setting up AfterMap but I'm still having the same issue:

config.CreateMap<AddPropertyViewModel, Property>().AfterMap((s, d) => d.City = new City { id = s.City });

your property class has single object City but the other class has ienumerable ...

private IEnuermable<City> _cities {get; set;}

You should make both classes compatible to each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM