Can I reuse the connection from DataContext in Linq to Sql? - linq-to-sql

DataContext has Connection property of type DbConnection and I was wondering if I could re-use it. I've tried to use it creating a command using CreateCommand and using a reader off of it but I've gotten errors saying there is a pending transaction or something similar.
Basically I'm trying to find out if there is a best practice or guidance on re-using that connection object.
The connection string itself doesn't really help since I can't create a new connection object with the abstract type and I don't want the code to know the specific provider type either.
One alternative approach I'm thinking of doing is having my DataContext derived type to have members that provide a factory method to create a new connection using the same connection information.
FYI, this inquiry stems from the need to invoke an ad-hoc stored procedure through DataContext, not the design-time ExecuteMethodCall variety. I didn't know about ExecuteQuery and for now that suffices. But for other situations where ExecuteQuery is inadequate, I'd need the low-level data access using connection/command etc.

Why not turn it around, and instead supply connections to the datacontext by using the constructor that takes a connection as a parameter? That way you can control when connections are created and disposed, opened and closed, and can reuse them for other purposes without having to worry about the internal behavior of the L2S datacontext...

I can't say definitely, but a connection is a connection. Until it's been closed (or returned to the connection pool), it should be viable to use, whether via LINQ or other means.

Related

How to address Entity Framework Open DataReader Issue

After getting this error :
MySqlException: There is already an open DataReader associated with
this Connection which must be closed first.
I was unable to request or get result sets because i was querying while EF was still lazy loading other stuff that i had previously requested.
Found many possible solutions to address this issue which i have shared as an answer below.
If you don't mention the type loading in EF configuration, EF will by default use Lazy Loading.
There are various ways to over come the 'Connection is open issue':
By adding MARS to your EF connection string, please also read this before jumping into it.
Use 'USING' statement, but for this you need to create a new entity object every time it gets disposed.
Convert your result to Generics types or into local object types in my case i converted it ToList() which helped address my issue and i was able to request a new result set from the context.
I have a base class that provides me with the context object, which is why i didn't use Using statement to create new context every-time i wanted to query the context.
feel free to edit any mistakes, still learning about EF and its behavior.

PetaPoco Should I use MultipleActiveResultSets=True?

From time to time we receive the following database connection error from PetaPoco in an ASP.NET MVC 4 app:
There is already an open DataReader associated with this Command which must be closed first.;
System.Data; at System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)...
It seems like this happens as we get more load to the system.
Some suggestions we found as we researched were:
Do a PetaPoco Fetch instead of a Query
Add MultipleActiveResultSets=True to our connection string
Can someone with PetaPoco experience verify that these suggestions would help?
Any other suggestions to avoid the Exception would be appreciated.
Update 06/10/2013 We changed the Query to a Fetch and we have seen some improvement however we still sometimes see the error.
Does anyone know what drawbacks changing the connection string to MultipleActiveResultSets=True might have?
Be sure that you are creating the PetaPoco DB per request (not a static).
See: how to create a DAL using petapoco
Update 06/10/2013 All Fetch methods calls the Query method (see the source)
So changing one for the other has no effect on the error.
The drawbacks are listed on the MSDN and includes warnings with:
Statement Interleaving
Session Cache
Thread Safety
Connection Pooling
Parallel Execution
I have tried it personally and didn't got any drawbacks (depends on your app), but didn't get rid of the errors also.
The only thing that you can do to remove the error, it's follow your request code to find where in the code the statement is called twice, and then use other DB connection in that function.
Also, you can catch the error and then create a new db connection and try with that new one.
Sorry but not magic bullet here.

Transaction in Enterprise library

How to handle transaction within a scope using Enterprise library. I've 3 stored procedures, which I need to execute in a single scope. I dont want to use System.Transaction name space
You can call the BeginTransaction method on a connection object to get a DbTransaction object. Then use the Entlib Database object's overloads that take a DbTransaction. However, it's a giant pain to manage. You'll need to create and close least one connection manually rather than relying on Entlib to do the right thing, and you'll have to pass the DbTransaction object around to everything that needs it.
TransactionScope really is the right answer here. If you've got some blocking scenario that really prevents you from using it that isn't some brain-dead corporate policy, I'd love to know what it is.

Managing different developer's connection strings under LINQ to SQL

With my source in Subversion, I am having issues when 2 different computers have different connection strings.
The LINQ to SQL designer seems to only like having the same connection string.
Is it possible for the designer to use a connection string that varies since developers have different local configurations, but the actual usage in the web application pulls from the web.config?
Unfortunately, this is a huge source of pain with the LINQ to SQL designer. I do not know of a way to force visual studio to never add a default connection string when you drag tables or stored procedures onto the design surface.
We work around the issue thusly:
we never save our dev passwords
we never use the default connection string in code when newing up a DataContext
we can therefore "safely" ignore the multiple connection strings during sprints that touch the data layer
when things die down/become more stable, we delete the connection strings from the data context, either using properties of the designer surface itself or by editing the XML. At that point, it's up to the modifier of the data context to keep up with deleting the default connection strings.
Alas, this is not an ideal situation. Hopefully VS2010 will "fix" this issue.
I ran into this problem and found your question. Here's the solution we're now using:
Use a centralised Configuration class for retrieving config values from a particular location on the file system. This allows every machine where the code is running to use its own config values.
Create a partial class for the LINQ to SQL data context. Add a custom constructor that takes no parameters and retrieves the database connection string from the Configuration class described above.
For example:
public partial class MyCustomDBDataContext
{
public MyCustomDBDataContext() :
base(Configuration.GetDatabaseConnectionString())
{
}
}
This should now solve the problem both for developers and when deployed to test and production.
By following the guidelines on How Do I? Change Connection String of datacontext default constructor from web.config my application now uses different connectionstrings depending on if HttpContext.Current.Request is local or not.
//using System.Web.Configuration;
partial void OnCreated()
{
//Change this condition to your needs
var isLocal = HttpContext.Current.Request.IsLocal;
this.Connection.ConnectionString = WebConfigurationManager.ConnectionStrings[isLocal ? "localConnectionstring" : "otherConnectionstring"].ToString();
}

How to use transactions in DotNetNuke (entangled with L2S)?

I use L2S at my module. The problem occurs while I'm using the default DNN entities at the same TransactionScope with my L2S data access, then I get a DTC request which I want to avoid.
How can I share the connection/transaction for both DNN entities and my L2S data access?
Sadly, as stated here - transactions are currently not the strong part of DNN (5.1.X), thus L2S operations should not be entangled with DNN core operations to prevent transactions escalation.
I don't know about DNN, but the L2S datacontext has a constructor that takes a SqlConnection (well, a IDbConnection of a SqlConnection) as a parameter. So if you have a connection already established, just pass it in to the L2S datacontext when you create a new instance.