4

We've implemented the null object pattern in our domain model. We're using code first with fluent api to persist our domain model.

One of our entities has a navigation property - this navigation property is a FK and is where we use the null object pattern.

Our null object has the default 0 value for it's id. Is there a way with fluent api (or direct mappings) to tell EF 'if this is one of those null objects, REALLY throw null in the database fk field, and not that invalid 0 id'.

EDIT:

As an example, imagine you have a Student Entity, and a FavoriteSubject entity. A student has a reference to a FavoriteSubject, unless he has no FavoriteSubject, then the null object would be something like NoFavorite.

When we persist this to the database, we get the Id of NoFavorite (0) where we'd really like NULL in the db as NoFavorite is a null object (follows null object pattern).

Steve's a D
  • 3,801
  • 10
  • 39
  • 60
  • Are your entities your contract between your domain and application layers, or do you have domain objects that map to entities? – moarboilerplate Aug 25 '15 at 21:02
  • 1
    A code example would be nice. – NightOwl888 Aug 25 '15 at 21:02
  • @moarboilerplate our domain models/entities map to the database with fluent api. The application layer is as far as the domain model goes – Steve's a D Aug 25 '15 at 21:04
  • Okay, so your entities are your domain objects. You're going to have to get a little creative. See [here](http://stackoverflow.com/questions/19370104/convert-value-when-mapping). If that doesn't work for you, then the null object pattern may not be a good fit for your design. – moarboilerplate Aug 25 '15 at 21:17
  • The (not really ideal) alternative would be to encapsulate your entities in your domain layer and map them to a new set of domain objects, where you could perform custom mapping there. – moarboilerplate Aug 25 '15 at 21:24
  • I think you will bring down a lot of trouble with EF's change tracker on yourself if you do this. – Gert Arnold Aug 26 '15 at 13:18

0 Answers0