1

I've started to develop ASP.NET MVC application using Entity Framework and I wish to use DDD. It's my first time using DDD in ASP.NET (used until now in PHP), so I'm little confused. I'm using code-first approach, so I'm creating my entites in the core and then the DbContext in the Infrastructure.

My questions is about data annotations: Is it OK to annonate the entities in the core? with Required, DataType, etc. or I have to create entries with pure C# validation (in the setters and getters) and then create a map objects for the database creation?

For example, I got:

public class Account
{
    public string AccountName { get; set; }
}

Can I annonate the AccountName with [Required] or I need to create a map class which will just reflect the exact same properties in the Account class but will have attributes and that will be the class that I'll use in Entity Framework DbContext?

Thanks!

2 Answers2

2

Neither.

Your entities should have barely any public getters or setters. Domain model is a behavioral model, not a data model. Your entities should have private fields and methods that changes the entity state. Those methods should have a business meaning and should protect entities invariants (validate input). For example - we have UserAddress and want to change it. Is it just user.Address = newAddress? NO. What's the meaning of changing that? Maybe your User want to FixMistypedAddress(str). Or maybe your UserMoved(newLocation)? Different business rules may apply tho those scenarios. For example when UserMoved() we want to send him a champagne bottle, but not when he just fixed a typo. You should already see that there is no use of data annotations here because we don't just set properties but we do meaningful operations.

Entities should always be valid. That mean there should be no way to put it in an invalid state. Data annotations only allow you to check whether the object is valid or not. They not guarantee is will be valid all the time.

IMO Data annotations are fine for:

  1. Using Entity Framework in a CRUD application (no DDD applied)
  2. In DTO or ViewModels. In other words - for validating user forms, not entities.

So the first quiestion for you is: Are you doing CRUD or DDD?

1

I'd say either way is fine.

If you want a more pure approach you would create a buddy class that has the metadata on it however it is also acceptable to put it directly on the domain class.

In the end it comes down to how much you want to remain "pure" and how much extra work you want to put into maintaining buddy classes, not to say that it is a bad thing.

Community
  • 1
  • 1
Daniel Powell
  • 8,143
  • 11
  • 61
  • 108