Fluent Nhibernate Domain Driven Design - fluent-nhibernate

Hi Im curious about how DDD is really implemented using Fluent Nhibernate. for example I have an entity class called User and another class called UserProfile, as far as Im concerned UserProfile is not an entity class but a value type, and should not realy have an identity as such if not associated with a User entity. Now to implement practically the user profile will ideally be stored in a database table called UserProfile and I cant see how I can get away from having a unique Id for this table. I am also using FluentNhibernate as an ORM and I beleive THE UserProfile class needs to have an Id in order to be mapped correctly. So what happens to the concept of values types, aggregate root etc, Is it really possible to implement a true DDD with fluent Nhibernate or is it just that my understanding of DDD is poor. All I have really seen is a lot of theory about the whole thing, but I have not seen a project that really has true DDD using NHibernate. I am a bit confused now, any help is appreciated
Update
Okay after a bit of reading up I understand that repositores are used to manage Aggregate roots, clears up some of the issues but ultimately the userprofile class is not an aggregare root, so should I still give it a Id? it obviously needs one in the database table so Im assuming the class needs an Id as well. But does this not go against the principle of DDD? what is the way around this?

It will need an Id to be supported by your ORM (NHibernate), and that's perfectly fine. The distinction between Entities and Value Types is their concepts of identity and lifetime. Having an Id field is simply an implementation detail here.

Related

DDD with L2S or NHibernate... about persisting data of business objects

I have been working on my first experimental DDD project. The objective of this project is for me to get a feeling on the whole DDD concept. Oddly enough, as i have read it's the more difficult part, i find the ubiquitous language "translation" easier than the whole architecture itself, thus my question.
I have only used in my past projects L2S (Linq to SQL). My applications were not DDD per se but they do have a Business Object (aside from the ones that linq to sql generates) and i have a repository for this objects. For example,
public class Customer
{
public ID {get; set;}
public string Fullname {get; set;}
public Address address {get; set;}
public List<Invoices> invoices {get; set;}
}
Now, in L2S, i have to breakdown this class into three different queries and submit them into the database. I have a mapper (extension methods) to make my life "easier". Something like this.
public void AddCustomer(Customer customer)
{
// This customer i am passing is the business object
// For the sake of demo, i am going to avoid the whole attach(), check for ID, etc.
// I think you are going to get what i am trying to do here.
using{ var context = new L2SContext())
{
context.CustomerEntity.InsertOnSubmit(customer.ToEntity());
context.AddressEntity.InsertOnSubmit(customer.Address.ToEntity());
context.InvoicesEntity.InsertAllOnSubmit(customer.Invoices.ToEntity());
}
}
Ok. Later on i have a SubmitChanges() method in the context where i actually persist the data to the database.
Now, i don't know much, almost anything, about NHibernate. But looking at some examples, i am suspecting that NHibernate takes care of all that breakdown for you (because of the mapping?) so you only have to pass Customer and it will do the rest. Is that Correct?
I am willing to learn NHibernate if I really see a HUGE benefit from it.
Thank you for checking out my question.
EDIT: Have you heard of Codesmithtools.com? They have a framework generator for LinqToSql, EF, NHibernate. Has anyone tried their NHibernate? I have used PLINQO for LinqToSql but they add so much crap to the classes that i believe are unnecessary. Pretty much the classes are suit to be used, for bad programmers, as business classes, DTO, ViewModels, etc. All In One :). Terrible. BUT, they are really good at generating all that. i have to give them KUDOS for that.
A few points for NHibernate over Linq-2-SQL for DDD:
Persistence by reachability. This can also be called cascading saves, but it would allow you to persist the customer entity without having to explicitly insert them. This fits nicely with DDD because Customer would be an aggregate and Address would be a value object. In NHibernate, value objects are represented as component mappings and entities and aggregates as class mappings. Aggregates should be persisted and retrieved as single units and NHibernate allows you to do this.
Persistence ignorance. NHibernate allows you to design your classes as pure POCOs, without references to additional libraries. As far as I remember, L2S required a special type for collections, as well as requiring explicit foreign keys as properties. Note, that even with NHibernate persistence ignorance is an ideal, not a goal.
As pointed out by others, there is a steep learning curve to NHibernate. For example, lazy loading can be problematic. But it is worth it overall.
Your question is open-ended. It is obvious that you now how Linq-2-SQL works. As the first comment already said: yes NHibernate can provide cascading saves. But this is only the beginning... Please, first of all, check this question and answers (there are more than one interesting):
NHibernate vs LINQ to SQL
I am using NHibernate on my private projects as the first choice. If possible I prefer it on any project. But, I would like to append one more NOTE, from my experinece:
The biggest benefit is, that once you will learn and work with NHibernate, it won't be so much difficult to work with other ORM tool. On some projects you will (I did) meet Entity Framework on some LLBL Generator..., and (while we can blame that something in comparsion with NHibernate is missing;) we can quickly:
understand the domain, because ORM forces the Entity/Domain driven implementation
use standard patterns
Wish it helps and good luck with NHibernate. Learning curve is maybe slower then expected, but benefits await.

Symfony2 Denormalize XML data to Doctrine Entities With Relations

I'm using Symfony2 and Doctrine 2.0. I'm trying to read data from an XML feed and map this to new or existing entities in the database. When data in the XML feed changes I need update existing entities, but when the data is added I should create new entities.
In my entity classes I'm using the following denormalize methods to map the XML data to the entity's properties:
function denormalize(SerializerInterface $serializer, $data, $format = null)
(Defined in Symfony\Component\Serializer\Serializer called inside my Entity classes)
The docs for this method state that "It is important to understand that the denormalize() call should denormalize recursively all child objects of the implementor." and this is what I'm trying to do. However entities should not know about the EntityManager so how do I check, inside the denormalize() method if a related/child entity already exists or not?
Kind regards,
Matthew
It is indeed a bad idea to call the EntityManager in an entity (and, as far as I know, outside a controller).
I've never faced that problem, but if I were you I'd try to denormalize in one of your controllers, or if it really bothers you, in a service that you call in a controller, and to which you give your EntityManager (here again, best do it in the controller itself, or simply send your objects to the service so it can denormalize the xml "into" the objects).
Best would be to write a controller that works no matter the entity given.
Hope that helps!
I think my problem was in my approach and not really my code!!
Originally, each time I found an entity represented in the XML I would check (using the EntityManager) to see if it was new or existing BEFORE denormalizing it. I took this route because there is duplication in the XML and I was worried about creating duplicate entities in the EntityManager. Cheacking to see if an entity already existed meant I could update the existing entity rather than create a duplicate. Now with my new approach every time I find an entity represented in the XML I denormailze it into a new entity. Of course this creates duplication in the EntityManager, just as there is in the XML, but this can be handled later, hopefully..!
So far this is proving to be a better solution, although I am experiencing some issues when trying to merge the duplicate entities in the EntityManager using $em->merge(); and cascade={"persist", "merge"}. I've posted a new question about this here: Doctrine 2.1 - Relation Lost After ManyToMany Cascade Merge - Symfony2
Matthew

Unidirectional parent-child association not null

I have a class structure which is akin to a PurchaseOrder (parent) and PurchaseOrderLine (child) pattern, where the order lines will only be saved to the DB by saving the parent PurchaseOrder and will only ever be accessed via the parent too.
The DB has PurchaseOrderLine.PurchaseOrder set to not permit null values.
It seems from searching through the web that it is not possible to have a uni-directional association from PurchaseOrder via an IList property without having to have a property on the line pointing back when the child has a NOT NULL constraint for its PurchaseOrder column.
Is this really the case? It seems like one of the most basic things one would want to do with an ORM, I find it difficult to accept that a product as mature as NHibernate cannot handle such a basic scenario.
No it's not the case. Please see the example provided in the answer to this question: When to use inverse=false on NHibernate / Hibernate OneToMany relationships?
Well, it may be the case that you can't have unidirectional one-to-many relationship defined only on one side, but I'll argue with your statement that this is "one of the most basic things one would want to do with an ORM".
One of the most basic things would be to have unidirectional one-to-many defined only on many side - as it is natural for RDBM tables. And ORMs (despite the common misconception) are not intended (or able) to fully abstract domain model from underlying data source. Even if in some cases they can, the database side suffers from select N+1 problems or very ineffective queries.
Defining one-to-many at one side makes an impression that i.e. counting the collection is cheap. It is the case with plain object graphs, but not with NHibernate entities, as reading collection causes (at least one) call to the database. Eager fetching from one side is also not able to properly use database join mechanism in the way it's intended to be used (opposite to eager fetch from many side).
Even if I don't agree with a lot of arguments, I think it is useful to read some of the articles saying that "ORM is an anti-pattern", like this one. They helped me to leverage the way I think about ORMs and make me think about ORMs as a compromise between two not matching paradigms, but not the way to hide one behind another.
This can now be achieved in NH3 using the Not.KeyNullable()
this.HasMany(x => x.Actions)
.Access.BackingField()
.KeyColumn("[Application]")
.Not.KeyNullable()
.Cascade.AllDeleteOrphan();

mapping entities with relations backed by obfuscated fields with NHibernate

And here goes yet another question on NHibernate.
This one most likely doesn't have a desired answer, but still - let's give it a try.
I'm currently putting all the efforts into mapping a domain model onto the database using NHibernate. This domain model comes from a framework which is heavily obfuscated. (Not that I have worked a lot with obfuscated code before, but this one in most of the places can be translated neither by Reflector, nor by Resharper.)
Everything went more or less fine until I faced an entity with a required many-to-one relationship represented by a property with no setter with obfuscated backed field.
Is it possible to reference this obfuscated field somehow? A very special IPropertyAccessor?
If not, how can I load a fully constructed entity? The only option to inject a related object is by using a constructor that accepts it. But at the time of instantiating of an entity being loaded, neither IInstantiator nor IInterceptor has any data of it apart from the key. Any other extension points that suit my need?
To allow NHibernate to access your field instead of property you can use this in your mappings:
access="field"

DDD: Should everything fit into either Entity or Value Object?

I'm trying to follow DDD, or a least my limited understanding of it.
I'm having trouble fitting a few things into the DDD boxes though.
An example: I have a User Entity. This user Entity has a reference to a UserPreferencesInfo object - this is just a class which contains a bunch of properties regarding user preferences. These properties are fairly unrelated, other than the fact that they are all user preferences (unlike say an Address VO, where all the properties form a meaningful whole).
Question is - what is this UserPreferencesInfo object?
1) Obviously it's not an Entity (I'm just storing it as 'component' in fluent nhibernate speak (i.e. in the same DB table as the User entity).
2) VO? I understand that Value Object are supposed to be Immutable (so you cant cange them, just new them up). This makes complete sense when the object is an address for instance (the address properties form a meaningful 'whole'). But in the case of UserPreferencesInfo I don't think it makes sense. There could be 100 properties (Realistically) There could be maybe 20 properties on this object - why would I want to discard an recreate the object whenever I needed to change one property?
I feel like I need to break the rules here to get what I need, but I don't really like the idea of that (it's a slippery slope!). Am I missing something here?
Thanks
Answer 1 (the practical one)
I'm a huge proponent of DDD, but don't force it. You've already recognised that immutable VOs add more work than is required. DDD is designed to harness complexity, but in this case there is very little complexity to manage.
I would simply treat UserPreferencesInfo as an Entity, and reference it from the User aggregate. Whether you store it as a Component or in a separate table is your choice.
IMHO, the whole Entity vs VO debate can be rendered moot. It's highly unlikely that in 6 months time, another developer will look at your code and say "WTF! He's not using immutable VOs! What the heck was he thinking!!".
Answer 2 (the DDD purist)
Is UserPreferencesInfo actually part of the business domain? Others have mentioned disecting this object. But if you stick to pure DDD, you might need to determine which preferences belong to which Bounded Context.
This in turn could lead to adding Service Layers, and before you know it, you've over-engineered the solution for a very simple problem...
Here's my two cents. Short answer: UserPreferenceInfo is a value object because it describes the characteristics of an object. It's not an entity because there's no need to track an object instance over time.
Longer answer: an object with 100+ properties which are not related is not very DDD-ish. Try to group related properties together to form new VOs or you might discover new entities as well.
Another DDD smell is to have a lot of set properties in the first place. Try to find the essence of the action instead of only setting the value. Example:
// not ddd
employee.Salary = newSalary;
// more ddd
employee.GiveRaise(newSalary);
On the other hand you may very well have legitimate reasons to have a bunch of properties that are no more than getters and setters. But then there's probably simpler methods than DDD to solve the problem. There's nothing wrong with taking the best patterns and ideas from DDD but relax a little of all the "rules", especially for simpler domains.
I'd say a UserPreferenceInfo is actually a part of the User aggregate root. It should be the responsibility of the UserRepository to persist the User Aggregate Root.
Value objects only need to be newed up (in your object model) when their values are shared. A sample scenario for that would be if you check for a similar UserPreferenceInfo and associate the User with that instead of Inserting a new one everytime. Sharing Value Objects make sense if value object tables would get to large and raise speed/storage concerns. The price for sharing is paid on Insert.
It is reasonable to abstract this procedure in the DAL.
If you are not shraing value objects, there is nothing against updating.
As far as I understand, UserPreferenceInfo is a part of User entity. Ergo User entity is an Aggregate root which is retrieved or saved using UserRepository as a whole, along with UserPreferenceInfo and other objects.
Personally, I think that UserPreferenceInfo is entity type, since it has identity - it can be changed, saved and retrieved from repository and still be regarded as the same object (i.e. has identity). But it depends on your usage of it.
It doesn't matter IMHO how object is represented in the DAL - is it stored in a separate table or part of other table. One of the benefits of DDD is persistence ignorance and is ususally a good thing.
Of course, I may be wrong, I am new to DDD too.
Question is - what is this UserPreferencesInfo object?
I don't know how this case is supported by NHibernate, but some ORMs support special concepts for them. For example DataObjects.Net include Structures concept. It seems that you need something like this in NH.
First time ever posting on a blog. Hope I do it right.
Anyway, since you haven't showed us the UserPreferencesInfo object, I am not sure how it's constructed such that you can have a variable number of things in it.
If it were me, I'd make a single class called UserPreference, with id, userid, key, value, displaytype, and whatever other fields you may need in it. This is an entity. it has an id and is tied to a certain user.
Then in your user entity (the root I am assuming), have an ISet.
100 properties sounds like a lot.
Try breaking UserPreferenceInfo up into smaller (more cohesive) types, which likely/hopefully are manageable as VOs.