如何使用AutoMapper映射外键值?

时间:2013-03-14 23:15:12

标签: entity-framework asp.net-mvc-4 automapper

我目前正在运行Code-First Entity Framework的MVC项目中使用AutoMapper。

是否可以在AutoMapper中映射外键值?

例如,我在下面拆开了我的模型:

public class Account
{
    [Key]
    public int AccountID { get; set; }

    public int AccountTypeID { get; set; }

    //Not included in Account Table in Database
    //  -Get "Type" column from dbo.AccountType table
    public string AccountType { get; set; }
}

在我的帐户详细信息页面上,我想在页面上显示AccountType的名称而不是ID。 AccountTypeID是与我的数据库中的AccountType表相关的FK。

My Current对此的映射非常简单:

Mapper.CreateMap<Models.Account, DataLayer.Account>();
Mapper.CreateMap<DataLayer.Account, Models.Account>();

使用ForMember可以实现吗?或者我是否必须对我的模型进行一些更改以实现此目的?

1 个答案:

答案 0 :(得分:2)

将此添加到您的配置

Mapper.CreateMap<AccountType, string>().ConvertUsing(a => a.Name);