Click here to Skip to main content
15,922,155 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a web service that exposes operations to and from a database. I'm using Entity Framework 4 for the DAL.
I'm wondering what would be the best way to handle operations to and from the database. Would it be best not to keep alive an instance of the ObjectContext and instead create one for each operation done to the database? This seems to be a very bad way to handle this, but i can't think of another way to keep up with the changes made to the database.
If i keep the same context alive, how will it know when data has been modified? I understand that when querying the database, the ObjectContext just checks if records have been added or deleted, by checking the Primary Key fields (am i correct? ). In that case, i have to explicitly tell it to refresh a particular object, which is not very practical.
I'm thinking of a solution where a timestamp column is used, and the objectcontext checks that column for changes. If that column is modified, it refreshes the data. Is such a solution built inside Entity Framework 4? Or does anyone have any other suggestions on how i can always get the latest data from the database without recreating the ObjectContext for each request?
Posted

1 solution

The Entity Framework (and Linq to Sql) data contexts are based upon the unit of work pattern so you only use it for what you need to do. It is never a good practice to hold on to data contexts. Don't worry about connection pooling and loading new object contexts or change management because EF is specifically designed and optimized for such use.

You should concentrate on the specific task you need to do then release the object context. Also, you should only worry about performance when you discover a performance problem, otherwise you will cause all sorts of unnecessary overhead and work.

If for some very strange reason you need to hold the object context open across the web there is a refresh method. I strongly advise not to do that, simply request only the data you need when you need it.

I hope this is of some help to you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900