在 asp.net 样板文件中自动映射一对一外键

Auto mapping one to one foreign keys in asp.net boilerplate

假设我有以下 class 结构:

public class Pizza
{
    public int Id { get; set; }
    public virtual PizzaType PizzaType { get; set; }
}

public class PizzaType
{
    public int Id { get; set; }
    public string Name { get; set; }
}

现在,我需要一个 DTO class,这样我就可以将对象传递给 UI 进行编辑,然后传递回服务以保存到数据库中。因此:

[AutoMap(typeof(Pizza))]
public class PizzaEdit
{
    public int Id { get; set; }
    public int PizzaTypeId { get; set; }
}

目标是尽可能轻松地在 PizzaPizzaEdit 之间映射,以便可以在 UI 中对其进行编辑并保存回数据库。最好是 "just work".

我需要做什么才能使从 PizzaPizzaEdit 的映射生效并将 PizzaTypeId 包含在 DTO 对象中?

pizzaObj.MapTo<PizzaEdit>() 有效,但 PizzaTypeId 始终为空。

我愿意根据需要更改 class 结构。

只需将属性PizzaTypeId加到Pizzaclass,就会变成FKPizzaTypetable。

public class Pizza
{
    public int Id { get; set; }
    public virtual PizzaType PizzaType { get; set; }
    [ForeignKey("PizzaType")]
    public int PizzaTypeId { get; set; }
}

或没有 FK(NotMapped) 通过 LazyLoading:

public class Pizza
{
    public int Id { get; set; }
    public virtual PizzaType PizzaType { get; set; }
    [NotMapped]
    public int PizzaTypeId { get { return PizzaType.Id; } }
}