简体   繁体   中英

Automapping to EntityKeys in Entity Framework

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.

I came across the following blog that explains the nature of my problem and solves it by way to Foreign Key Properties supported in EF4.0

http://blogs.msdn.com/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx

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