Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key properties in domain entities

In Domain-Driven Design, the domain model should be completely unbeknownst of any data persistent specifics.

Let's say that an Employee belongs to a Department. The domain entities could look like this:

public Employee
{
    public string EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName{ get; set; }
    public Department Department { get; set; }
    public int DepartmentId { get; set; }
}

public Department
{
    public string DepartmentId { get; set; }
    public string Name{ get; set; }
}

Is Employee.DepartmentId really relevant in the domain model or is that an infrastructure storage detail?

Surely Employee.Department is the relationship that matters at this level?

In my case, these entities will be stored in a SQL database and the data will be retrieved by Entity Framework, so an Employee.DepartmentId column will exist in the database.

like image 280
Dave New Avatar asked Dec 12 '13 07:12

Dave New


1 Answers

Life is easier in the Entity Framework if you use foreign keys:

Why does Entity Framework Reinsert Existing Objects into My Database?

Making Do with Absent Foreign Keys

And you are absolutely correct to say that the foreign key is not really relevant to the domain model. It is part of the persistence model.

So you need to decide which camp to join. Are you a purist or a pragmatist? Separate domain models and persistence models or not?

ORM Entities vs. Domain Entities under Entity Framework 6.0

like image 72
Colin Avatar answered Sep 28 '22 21:09

Colin