【问题标题】:How do I use AutoMapper to map Foreign Key Values?如何使用 AutoMapper 映射外键值?
【发布时间】:2013-03-14 23:15:11
【问题描述】:

我目前在运行 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。

我当前的映射非常简单:

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

这可以通过使用 ForMember 来实现吗?或者我是否也必须对我的模型进行一些更改才能实现这一点?

【问题讨论】:

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


【解决方案1】:

将此添加到您的配置中

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多