From MSDN (DataContext Constructor (IDbConnection)
):
If you provide an open connection, the
DataContext will not close it.
Therefore, do not instantiate a
DataContext with an open connection
unless you have a good reason to do
this.
So basically, it looks like your connections are waiting for GC to finalize them before they will be released. If you have lots of code that does this, one approach might be to overide Dispose()
in the data-context's partial class, and close the connection - just be sure to document that the data-context assumes ownership of the connection!
protected override void Dispose(bool disposing)
{
if(disposing && this.Connection != null && this.Connection.State == ConnectionState.Open)
{
this.Connection.Close();
this.Connection.Dispose();
}
base.Dispose(disposing);
}
Personally, I would happily give it (regular data-context, w/o the hack above) an open connection as long as I was "using" the connection (allowing me to perform multiple operations) - i.e.
using(var conn = GetConnection())
{
// snip: some stuff involving conn
using(var ctx = new FooContext(conn))
{
// snip: some stuff involving ctx
}
// snip: some more stuff involving conn
}
From "Fixing LINQ Error: Sequence contains no elements":
When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First()
or Single()
command rather than FirstOrDefault()
and SingleOrDefault()
.
This can also be caused by the following commands:
FirstAsync()
SingleAsync()
Last()
LastAsync()
Max()
Min()
Average()
Aggregate()
Best Answer
perhaps your field/properties mapping in your DBML is not correct