i have a problem with some data i retrievied from db with linq. When I try to access data I obtain the following exception: System.ObjectDisposedException : The istance of ObjectContext was deleted and is not possible to use it again for action that need a connection. This is the code:
using (ProvaDbEntities DBEntities =
new ProvaDbEntities(Utilities.ToEntitiesConnectionString()))
{
ObjectQuery<site> sites = DBEntities.site;
IEnumerable<site> q = 开发者_如何学Cfrom site in sites
select site;
{
ObjectQuery<auction> auctions = DBEntities.auction;
IEnumerable<auction> q1 = from auction in auctions
where auction.site == this.Name
select auction;
IEnumerable<IAuction> res = q1.Cast<IAuction>();
return res;
}
}
catch(Exception e)
{
throw new UnavailableDbException("[GetAuctions]" + e.Message);
}
Someone can help me??? Tanks Fabio
Yes - you're returning a result which will be lazily evaluated - but you're disposing of the data context which would be used to fetch the results.
Options:
- Load the results eagerly, e.g. by calling
ToList
on the result - Don't dispose of the context (I don't know what the situation is in the Entity Framework; you could get away with this in LINQ to SQL, but it may not be a good idea in EF)
- Dispose of the context when you're finished with the data
In this case I'd suggest using the first option - it'll be safe and simple. As you're already filtering the results and you're casting to IEnumerable<IAuction>
anyway, you're unlikely to get the normal downsides of materializing the query early. (If it were still IQueryable<T>
, you'd be throwing away the ability to add extra bits to the query and them still be translated to SQL.)
精彩评论