If I map my Domain objects to linq Entities will I now not be able to track changes when saving my domain objects? So for any change in my model that i wish to make, once I map the object to linq entities for submission to db, all object values will be submitted to the db by linq since it it goes through a mapping first? Or would the object tracking here still be utilized?
Depends on the O/R mapper you're using. You're referring to entity framework which doesn't do any change tracking inside the entity and therefore it needs help from you when you re-attach an entity which previously was fetched from the db (so it knows it's not new).
Here's an article from microsoft about CRUD operations in multi-tiered environments (similiar issues to your Domain mapping scenario).
Check out the Update - With Complete Entities for the way to do change tracking yourself.
There's another technique, where you attach the entity as unmodified, and then .Refresh() with Keep Current Values - replacing the original. This would allow you to Insert/Update/Do Nothing as appropriate at the cost of a database roundtrip.
Related
I have a collection of entities from the database that is shown to the user (web application with Spring). The user can change one or more entities(rows) and submit all his changes together to the server (not one-by-one).
What is the recommended way of updating only the rows that have changed using Hibernate? At the moment I am storing the original collection as a property in the controller and saving only the rows that have been changed by comparing the entities of the collection with the old ones, one-by-one (incrementing a counter that is returned to the user). I suppose that storing the collection on the controller is not a good practice. Is there a better way to achieve this?
I also want to use optimistic locking (automatic versioning) if that makes any difference.
For application developers, I suppose the traditional paradigm for writing an application with domain objects that can be persisted to an underlying data store (SQL database for arguments sake), is to write the domain objects and then write (or generate) the table structure. There is a tight coupling between what the domain object looks like and what the structure of underlying data store looks like. So if you want to add a piece of information to your domain object, you add the field to your code and then add a column to the appropriate database table. All familiar?
This is all well and good for data stores that have a well defined structure (I'm mainly talking about SQL databases whereby the tables and columns are pre-defined and fixed), but now a number of alternatives to the ubiquitous SQL database exist and these often do not constrain the data in this way. For instance, MongoDB is a NoSQL database whereby you divide data into collections but aside from that there is no structuring of the data. You don't define new columns when you want to add a new field.
Now to the question: given the flexibility of a data store like MongoDB, how would one go about achieving a similar kind of flexibility in the domain objects that represent this data? So for instance if I'm using Spring and creating my own domain obejcts, when I add a "middleName" field to my data, how can I avoid having to add a "middleName" field to my domain object? I'm looking for some kind of mechanism/approach/framework to dynamically inspect the data and have access to it in my domain object without having to make a code change every time. All ideas welcome.
I think you have a couple of choices:
You can use a dynamic programming language and not have domain objects (clojure for example)
If you're fixed on using java, the mongo java driver returns data in DBObject which is essentially a Map. So the default behavior already provides what you want. It's only when you map the DBObject into domain objects, using a library like morphia (or spring-data), that you even have to worry about domain objects at all.
But, if I was using java, I would stick with the standard convention of domain objects mapped via morphia, because I think adding a field is a very minor inconvenience when compared against the benefits.
I think the question is inherintly paradoxical-
On one hand, you want to have domain objects, i.e. objects that represent the data (and behaviour) of your problem domain.
On the other hand, you say that you don't want your domain objects to be explicitly influenced by changes to the data.
But when you have objects that represent your problem domain, you want to do just that- to represent your problem domain.
So that if, for example, middle name is added, then your representation of the real-life 'User' entity should change to accomodate this change to the real-life user; perhaps not only by adding this piece of data to your object, but also adding some related behaviour (validation of middle name, or some functionality related to it).
In essense, what I'm trying to say here is that when you have (classic OO) domain objects, you may need to change your behaviour / functionality along with your data, and since you don't have any automatic way of changing your behaviour, the question of automatically changing your data becomes irrelevant.
If you don't want behaviour associated with your data, then you essentialy have DTOs, and #Kevin's answer is what you're looking for.
Honestly, it sounds more like you're looking for some kind of blackbox DTO where, like you describe, fields are added or removed "arbitrarily" depending on the data. This makes me inclined to suggest a simple Map to do the job. You can't really have a domain-driven design if your domain model is constantly changing.
Given an MVC3 app using the ViewModel pattern and the Repository pattern with Entity Framework.
If I have a create and update view each composed of multiple entities, what is the best practice for saving the data?
Should I save the date using an abstracted service layer which will save the data for each entity with its respective repository or should I save the data in the repository using a stored procedure?
I'm open to any suggestions or recommendations.
Thanks in advance!
This is one of those cases where a DDD/CQRS approach makes most sense. Simply put, you have some business objects which models a specific behavior (an aggregate). There is one object in chrage called the Aggregate Root (AR) which has explicit boundaries. When you want to save it, you send the whole AR to the repository which then saves everything as a transaction.
The workflow
User sends the data via a view model. The controller will then retrieve the AR from the repository or creates if it's new . THe input data is mapped to the AR, usually via an AR method. IF the AR finds that the data or the result of it, breaks some business rules then it should throw an exception (we assume that basic validation was already performed automatically by asp.net mvc).
If everything is ok, the controller will send the AR to the repo which then it will proceed to map the AR to EF entities and then saves it, all within a transaction.
THis is in a nutshell how I'd do it. Of course, I'd actually implement it a bit different, but the concepts are the same. THe important part is to send all the data to the AR which will know how to handle relationships.
Important points
Note that I've mentioned EF only after the AR got to the repo. This means, the AR has no relation to EF entities is completely separated and serves the actually business model. Only after the model is updated, we care about EF and ONLY within the repo (because EF is an implementation detail of the repo). The repo only transfers (maps basically) AR data to the relevant EF entities and then saves the entities.
It's important to have a very clear distinction between the business (domain) model and the persistence modewl (EF entities). Don't use EF to handle business rules, use it only to stare/retrieve data from db. EF was made to abstract RDBMS access only, use it as a virtual OOP database.
You've mentioned the ViewModel pattern. I haven't heard about such a pattern, everytime you're using MVC you're already using ViewModels. One again, the trick is NOT to use EF entities as ViewModels. Use 'dumb' view models fitted for the views. Populate the VM via a specialized Queries repository which will return directly VM parts. The repo will query EF entities and then return those VM bits which are simple DTO's. That's because you don't need validation and business rules when showing data.
I think it is a good practice to keep the layers and especially each layer's model separated. For updating stuff, use complex business objects(domain model) which will do the hard work and then only transfer their state to EF (via repository). For reading stuff, query EF and return simple DTOs fit for VM.
This is what CQRS is really about: don't try to fit different responsibilities (write and read) in a single model.
I have a Users table, Events table, and a mapping of UserEvents. In some parts of my code, I just need user-based stuff. In other parts, I need all of this information. (Especially: given a user, what are the details of each event they are subscribed to?)
If I have one repository just for users and another for users + events + userevents, then the auto-created users object is duplicated and the code won't compile until I rename one of them. This is possible but inconvenient. On the other hand, if I only have one repository with all 3 tables, when I just want user info, will it be expensive due to linq getting all the associated data with that user id?
In Linq2Sql, is it more expensive if you have more tables in a single dbml/repository?
Linq2Sql uses lazy loading to get additional information. I believe it can be configured to fetch all at once, but that is not the default behavior. If you ask for a user, you will not get events unless you specifically ask for them.
I have a project with 100+ tables in the dbml, as far as I can tell this does not effect the the time to instanciate the datacontext class.
in early development stages the database is subject to continuous changes. I'm toying around with LinqToSQL and in most cases the Entity Model is just a 1:1 representation of the DB.
How can i keep the model up to date with the db changes?
Thanks.
I noticed that there is an "update model from database" command available if you right-click the Entity Framework design surface. I couldn't find such a thing for LINQ to SQL, so you might have to maintain by hand.
OTOH, it's just XML, so you could "just write some code".
The other thing to add is that I prefer the fact that in EF, I don't have to keep up to date with the physical database. I'm defining the entities that developers will use to access the data, and separately I'm defining the mapping between those entities and the logical database structure.
They don't need to be the same. If I want to split a table into two, or combine two entities into one table, I can do this, without requiring developers to rewrite their code.