Suppose I have code in this form:
using (var dc = new MyDataContext()) {
// ...code that may or may not look up objects via Linq-to-SQL...
// ...code that may or may not *update* objects via Linq-to-SQL...
// and call SubmitChanges...
// Non-Linq-to-SQL code:
dc.Connection.Open(); // <== I believe I need to do this
using (SqlCommand cmd = dc.Connection.CreateCommand()) {
// ...set up the command...
using (SqlDataReader reader = cmd.ExecuteReader()) {
// ...use the reader here...
}
}
// ...more code that may or may not look up objects via Linq-to-SQL...
// ...more code that may or may not *update* objects via Linq-to-SQL...
// and call SubmitChanges...
}
Is that safe, e.g., am I allowed to co-opt the connection like that? Am I correct that I have to call Open
in case the code above hasn't had to do any DB calls?
This MSDN page seems to say that this is fine:
The DataContext is the main conduit by which you connect to a database, retrieve objects from it, and submit changes back to it. You use the DataContext just as you would use an ADO.NET SqlConnection.
(Yes, this is all in the context of a single unit of work, in keeping with the concept of DataContext
. It's just that it's a complex unit of work.)
If it matters, I'm stuck in .Net 3.5 for this project.