I am reading about which is the recommended life for the data context, but I still have some doubts about the best option.
In general, the conclusion that I see is that in desktop applications the life of the data context should be the life of the form, and in WCF applications the life should be the life of the session.
The reason, if I understand, it's that the life of the data context should be enough large to have the advantages of the unit of work of the context but no very large to lost its benefits.
But, for example, if I read some data from the data base and the data context is create as property of the form in a desktop application, if I do changes, I only have to change the values in the entities of the data context and call the savechanges() method and EF save the changes in the data context. So I have two interactions with the data base, one to get the data and other to save the changes.
However, in this way, the data context can grow very large and also there is more probabilities that occur concurrency issues, I mean that since I load the data, make the changes and save the data, other user has time to modify the information.
If I use a data context for each operation, I read the data with a data context that is dispose, make changes to the information in local variables and then, when I save the changes, I must use other data context, which receive again the entities, I must search for the entities for pass the information from my local variables to the entities and then save the changes.
In this case I have three interactions with the data base so is less efficient and the database must to do more work. One to get the results and pass the information to local variables, other to get again the results and pass the information from local variables to the context and finally the save of the changes. Also, I must do extra work to search for the entities in the second data context to pass the changes from the local variables to the new context.
However, concurrence issues have less probabilities to occur, because is only the time elapsed between the load of the data in the second data context and pass the changes from the local variables to the context.
So, which is the best option to work with the data context, in desktop applications and WCF applications? Perhaps I am doing a wrong using of the data context?
Perhaps if I use the second approach, and my locals variables are entities too, I can create a second data context, and instead of load entities from the database, I can add the local entities directly, changing its state to add, changed or deleted and then the data context can save the changes?