I am asking in order to know what is the best practice for such cases. I am using EF4.
I have two entities called “Note” and “Product”. I have another entity called “Stock”.
Note has many Products and each Product can be in one Note only (Product must have a Note).
Whenever I insert, Delete or Update a Product, I have to update the relevant Stock entity according to the Note attached to the Product.
In the InsertProduct() method I insert the Product and then update the relevant Stock. In case the Product will break the Stock rules – I get an exception and the operation will abort as should be.
In the InsertNote() method, I cannot insert the Note because such thing will insert automatically the attached Products and for each Product I need to update the Stock and validate Stock rules (as described above). So before the Note insertion I loop through all the Products and call to InsertProduct(). After that I insert the note.
Until here two questions:
-
Does the things should be like that? Do I need to manually insert
each Product before I insert the Note? How does this settle with the
fact Product must be attached to exists Note (in the time of
insertion the Products, the Note wasn’t inserted)? -
Where should I put the InsertNote() and InsertProduct() methods?
each one of them deals with Note, Product and Stock entities. Should I create something like NoteService and ProductService classes or should I put them in one big service class?
In the question I asked here, I got an answer that describe how to create events like OnBeforeInsert(). Is this implementation is fine with my needs to update the Stock after insert Product?
I’m not quite sure I fully grasp what you’re trying to do and what it means to validate Stock rules and update stocks. But it seems like you’re trying to reuse InsertProduct from InsertNote when you shouldn’t be.
It seems like InsertNote should
SaveChanges()and InsertProduct should
SaveChanges()In other words, both these methods would reuse just the rule checking part. InsertProduct might be better renamed to UpdateProductsOfNote because it sounds like Note is an aggregate root of your model (In DDD, you do persistence/repository operations against the aggregate).
As to where these methods live, if they are not too complex, adding them to a repository/data access class (that owns the EF context object) would be ok. It does seem like they have quite a few rules associated with them. If so, some sort of domain service would probably be a better choice. It seems like much of the rules aren’t simply to support persistence. If you relocate these methods then you may not need to handle
ObjectContextevents as you asked in the post you referenced.