3

I am struggling with pure implementation of Aggregate root with Entity Framework Code First. Suppose we have a standard problem of Order and OrderItem, the latter being the child of the former. We need to have a read only collection of OrderItem items in Order class so we can (by design) control the Adding, Removing or Updating of OrderItems in it's aggregate root (ie Order class).

  1. How do we implement this list of OrderItem(s)? This list needs to be read-only so that other developers don't try adding OrderItem(s) inside the list by hand, avoiding methods that should be used instead.

  2. How do we map that collection in EF Code First? Private properties are not mappable.

Milivoj Milani
  • 315
  • 2
  • 11
  • You can map private members: http://stackoverflow.com/a/13810766/861716 – Gert Arnold Feb 17 '14 at 20:16
  • 1
    That's true, but that's hardly a DDD solution. You add coupling between domain classes and underlying persistence mechanism. – Milivoj Milani Feb 18 '14 at 07:38
  • 3
    The hard truth is that the class model belonging to an Entity Framekwork context is a [data layer in the first place](http://stackoverflow.com/a/18113611/861716). Everything must be optimized to facilitate data access (virtual members, Id properties for identification and foreign keys, bidirectional relationships, classes closely resembling database tables). My opinion is: you can't do DDD with an EF class model, the ORM will have a big footprint one way or another. – Gert Arnold Feb 18 '14 at 08:31
  • @GertArnold Yes, it seems that way. I agree with you. – Milivoj Milani Feb 18 '14 at 09:13

1 Answers1

1
  1. How do we implement this list of OrderItem(s)? This list needs to be read-only so that other developers don't try adding OrderItem(s) inside the list by hand, avoiding methods that should be used instead.

A read only list will not prevent other developers from Adding and Removing items to it. It will only prevent them from changing the reference pointer of OrderItems.

What you can do is make the list private, and have a method AddItem, RemoveItem and UpdateItem on Order and an IEnumerable getter of the list for iteration purposes.

  1. How do we map that collection in EF Code First? Private properties are not mappable.

I've never used EF, but from having done some DDD before, it's useful to have one set of entities for your application and logic, your true domain model, and another set of entities for your data access framework, in this case EF. And use something like AutoMapper to map from your EF entities to your domain entities.

You don't have to always have two set of entities, but for those that are problematic like this one, make the entity EF wants, and just add the extra step of mapping from object to object(s).

Didier A.
  • 4,609
  • 2
  • 43
  • 45