I have code similar to the following.
using (MyEntities context = new MyEntities())
{
var activities = from act in context.Activities
where act.ActTwittered == false
select new { act.ActID, act.ActTitle, act.Category, act.ActDateTime, act.Location };
foreach (var activity in activities)
{
/* ... */
}
}
This seems to work fine but my loop has a lot of processing. I’m concerned that I’m leaving a database connection or other resources open during this processing.
I tried declaring var activities before the using statement so I could process the data after the using statement, but this variable must be initialized where it is declared.
Could someone who understands the inner workings of EF tell me if there are problems doing lengthy processing while an EF context is “alive”, and how I make alleviate these problems.
While I’m at it, perhaps you could also comment on the fact that I use act.Category.CatName within the loop. This is a value from a related table. Am I better to use a join in my EF query so I get the data all at once rather than forcing another (?) database access to get the related data?
Your problem is in wanting the anonymous type to be accessible outside of its context. You can use a specific type for your results and get the flexibility to access the values anywhere.
. . .