Automapping to EntityKeys in Entity Framework
        Posted  
        
            by CodeGrue
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by CodeGrue
        
        
        
        Published on 2010-04-29T16:26:41Z
        Indexed on 
            2010/05/04
            12:08 UTC
        
        
        Read the original article
        Hit count: 328
        
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.
© Stack Overflow or respective owner