Question

So I need some advice and insight here. Thanks in advance for your thoughts.

I have developed static functions that return a single record from a LINQ entity. Like so:

FooRecord GetRecord(Guid id)
{
   using(var dc = new FooDataContext())
       return dc.FooRecords.Where(a => a.Id == id).First();
}

This throws an exception because the DataContext is already disposed, which creates problems with deferred execution. This works:

FooRecord GetRecord(Guid id)
{
       var dc = new FooDataContext();
       return dc.FooRecords.Where(a => a.Id == id).First();
}

I am worried. How quickly will the DataContext be disposed? Obviously if I grab the record immediately this won't cause an issue. However, say I need to grab a record through association:

var record = Data.FooRecord.GetRecord(id);
//Do a bunch of stuff...
//Now we grab the related record from another entity
var barRecord = record.BarRecord

Is there a risk the DataContext be gone by this point? Any advice?

Was it helpful?

Solution

You basically do not need to Dispose() your DataContext for the reasons discussed here:

When should I dispose of a data context

http://csharpindepth.com/ViewNote.aspx?NoteID=89

The main reason for implementing IDisposable on a type is to dispose of any unmanaged resources. The only unmanaged resource allocated by the DataContext is the underlying database connection, but the DataContext already takes care of opening and closing the connection as needed.

The main thing you want to avoid is returning an IEnumerable collection and then never enumerating it, as this will cause the connection to remain open indefinitely. However, since you are only returning a single object, you shouldn't have to worry about this.

Also note that if access any relationship property on the returned object it may cause the connection to be momentarily reopened so that the property can be lazy loaded. You can avoid this by using DataLoadOptions.LoadWith() with your DataContext to eager-load any properties you intend to access. See http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx

As to the last part of the question, if the returned entities contain properties that can be lazy loaded, then they will contain internal references to back the DataContext that will keep it in memory. Once you have no more references to these entities, then the DataContext will of course be garbage-collected just like any other object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top