Posted almost 8 years ago
ASPMVC vs. Rails (DBContext vs. ActiveRecord)
The primary purpose of this post is to facilitate a discussion I was am having on twitter with stuartleeks.
I wrote it fairly quickly and primarily wanted to use this post as a venue for discussion (via comments) rather than to provide consumable content. So don’t judge for the quality/depth of the content. Hopefully the discussion will be pretty interesting though.
ASPMVC centralizes the interaction between models and the DB in a class called DBContext. ModelState tracks all loaded entities, and save is called on the DBContext class as opposed to being called on individual models.
The disadvantages of this approach that I’ve ran into so far are…
Callbacks/Overrides on events are not model specific
In Rails, I can create onSave hooks on any model I choose. This is valuable for setting default values, manipulating data, etc. In ASPMVC this is done by overloading the SaveChanges method in the DBContext class. In the latter case, in order to get model specific functionality you have to if/else over the DBEntities within model state to manipulate the elements that pertain to specific models. This is further complicated by the fact that one cannot access the model directly from DBContext. DBEntities do not have direct access to the model class, therefore it is difficult to separate concerns. For example, I have a getTableName method in my model class that I had to duplicate in the DBContext class.
Element not tracked in model state
I haven’t done my due diligence to determine what the actual cause of this error was, but I ran into this error when attempting to create a new model and persist it from within the SaveChanges method. I ended up approaching the problem another way, but I believe the problem was due to the fact that I was creating a new model and calling SaveChanges from with the SaveChanges method (no infinite loop due to the fact that the second call was inside a control statement). This problem is easily handled in a Rails callback.
I hope this isn’t difficult to follow. I wrote it fairly quickly. If it is, feel free to comment and I can elaborate on any confusing points.