Dave New
Dave New

Reputation: 40032

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.

Upvotes: 7

Views: 3940

Answers (2)

lays
lays

Reputation: 158

I know this question is almost 10 years now. Meanwhile, I wanted to say that if your app is responsible for assigning the ids (usually in services or directly on the domain object or anything not related to the persistence layer linked to your database), Foreign keys are definitely part of your business logic layer and hence are entirely part of your domain entities.

Upvotes: 0

Colin
Colin

Reputation: 22595

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

Upvotes: 6

Related Questions