0

So I am reading this DDD book and at the same time designing a new system. In the DDD book they have an example where the entity have private members such as ID and other values.

Lets say as an example we have a user entity and it has id and a collection of courses it has the right to attend.

Then in DDD style they use something like GrantRightTo(Course c) if we say are on a user entity. And that is all good and well, because in the function I can now check any business rules like if the user is signed up to too many courses. Smart!

The alternative being that anyone has permission to the collection of courses but then the controllers need to know business rules which is not good.

Now here is the problem with EF code first, I can't get my collection of courses to be private/protected like my book does it and still be persisted (dbcontext) So what to do?

I could of course have the collection public and still have a method like GrantRightTo, but then other developers might do it the wrong way, so not ideal.

What to do?

Rickard Liljeberg
  • 966
  • 1
  • 12
  • 39

1 Answers1

2

The best way to do this is to map your database model with DTO's (data transfer object).

You would create an extra layer with a DTO-model. You real Domain Model could then be based on this DB Model. In your Domain Model you can than abstract away the differences in the underlying model.

This also has a disadvantage in that you would need to maintain both models if there are vertical changes in your projects. However, it also allows your domain model to change independently from your physical database model.

Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • Thank you for the answer. It does sound a bit annoying to add another layer which has to be maintained. Is this the recommended path to go, or should I simply look at a different design altogether? – Rickard Liljeberg Apr 21 '13 at 11:04
  • It depends a lot on your application. This is one way to go, but as I said, there are advantages and disadvantages. You should really look at your specific application and see what is the best for your situation. Unfortunately, there's no silver bullet here – Kenneth Apr 21 '13 at 11:06
  • How about this solution: http://blog.oneunicorn.com/2012/03/26/code-first-data-annotations-on-non-public-properties/ True there is some code in the entity that is about storing but it's still theoretically storage agnostic. and would remove the need for an extra layer. – Rickard Liljeberg Apr 21 '13 at 13:37
  • This of course is also a valid solution. If adding a new layer would add to much complexity I'd go for that – Kenneth Apr 21 '13 at 13:45