Handling relations when mapping DTOs to EF entities

asp.net-core-webapi automapper c# dto entity-framework-core

Question

In my DTOs, I send Ids instead of entire objects to assign/relate one object to another. The problem is my mapping code will need access to the database to handle this because my entity classes don't have BarId property.

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; }
}

This can probably be solved by adding additional BarId property to my entity class, that way I don't couple data access with my mapper.

But the question arises: if bar with specified id doesn't exist can this be handled in some reasonable way to return the custom error message?

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

Is it fine to access database in my mapping code and handle these assignments manually or is it better to leave it to the ORM by explicitly adding a foreign key property (BarId) in my entity class?

Also see: 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.

It seems like adding foreign key property is recommended so I guess I will choose this route.

1
0
8/7/2018 10:06:37 AM

Accepted Answer

no, not fine. if you are accessing the db this is most definitely not mapping code.

1
8/7/2018 10:08:34 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow