Executing e SQL ObjectQueries
You execute an ObjectQuery < EntityType > against an ObjectContext
instance to return an ObjectQuery < EntityType > . ObjectContext s are relatively weighty objects,
especially if they contain a large number of business object instances that have associated entities loaded
and have object change tracking enabled. Windows form apps that update the data store commonly
cache ObjectContext instances that have multiple changes to collection members or entity property
values and then apply the ObjectContext.SaveChanges() method to persist the changes to the data
store. ObjectContext lifetime in Web apps commonly is limited to a Unit of Work. Martin Fowler states
that the Unit of Work design pattern “ [m]aintains a list of objects affected by a business transaction and
coordinates the writing out of changes [to the data store] and the resolution of concurrency problems. ”
Thus, the minimum ObjectContext lifetime for a Web app is the duration of the simplest transaction
and the maximum could be the user ’ s session lifetime or the server cache duration.
There is no hard - and - fast rule or formula for optimizing ObjectContext lifetime, as you can see by
executing a Web search on the words ObjectContext lifetime . Daniel Simmons, a development
manager for EF, has written several blog posts ( http://blogs.msdn.com/dsimmons/ ) about
choosing the appropriate ObjectContext lifetime. (Search the blog for “ lifetime .” )
Most of this chapter ’ s examples have the option of repeating queries 1,000 times to increase elapsed time
resolution for performance comparisons. The queries don ’ t update data, so the pattern for sample
queries (without the outer for (int i = 0; i < tries; i++) ) repetition loop is:
C# 3.0
try
{
using (NorthwindEntities ocNwind =
new NorthwindEntities(“name=NorthwindEntities”))
{
ObjectQuery < Order > orderQuery(eSqlText, ocNwind, MergeOption.NoTracking);
foreach (Order order in orderQuery)
{
// Display the orders
}
}
}
catch (EntitySqlException exQry)
{
MessageBox.Show(exQry.Message, “Entity SQL Exception”);
}
catch (Exception exSys)
{
MessageBox.Show(exSys.Message, “Other Exception”);
}
No comments:
Post a Comment