将 DTO 映射到 EF 实体时处理关系

Handling relations when mapping DTOs to EF entities

在我的 DTO 中,我将 ID 而不是整个对象发送到 assign/relate 一个对象到另一个对象。问题是我的映射代码需要访问数据库才能处理这个问题,因为我的实体 classes 没有 BarId 属性.

public class FooDTO
{
    public int FooId { get; set; }
    public int BarId { get; set; }
}

public class Foo
{
    public int FooId { get; set; }
    public Bar Bar { get; set; }
}

这可能可以通过向我的实体 class 添加额外的 BarId 属性 来解决,这样我就不会将数据访问与我的映射器耦合。

但问题出现了:如果不存在具有指定 ID 的栏,是否可以通过某种合理的方式处理 return 自定义错误消息?

public class Foo
{
    public int FooId { get; set; }
    public int? BarId { get; set; }
    public Bar Bar { get; set; }
}

在我的映射代码中访问数据库并手动处理这些分配是否可以,还是通过在我的映射代码中显式添加外键 属性 (BarId) 将其留给 ORM 更好实体 class?

另见:https://docs.microsoft.com/en-us/ef/core/modeling/relationships#no-foreign-key-property

While it is recommended to have a foreign key property defined in the dependent entity class, it is not required.

好像建议加外键属性所以我想我会选择这条路。

不,不好。如果您正在访问数据库,这绝对不是映射代码。