Automapping to EntityKeys in Entity Framework
- by CodeGrue
Does anyone have a technique to automap (using Automapper) references to child entities. So say I have a ViewModel:
class AddressModel
{
int Id;
string Street;
StateModel State;
}
class StateModel
{
int Id;
string Name;
}
And I pass this into a repository to map to equivalent entities in Entity Framework. When Automapping, I want it to automap AddressModel.State.ID to the EntityKey of AddressEntity.StateReference. So hand crafted code would look like this:
addressEntity.Id = AddressModel.Id;
addressEntity.Street = AddressModel.Street
addressEntity.StateReference.EntityKey = new EntityKey("MyDB.States", "Id", AddressModel.State.Id);
Obviously, when automapper tries to assign an Address.State.Id to the equivalent in EF, an exception is thrown.