0

I am working on a report and wanted to generate an excel file from data. I have created a stored procedure which returns multiple datasets and because I am using EF which only supports single dataset, I opted to use below code

using (var connection = mydbcontext.Database.Connection)
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = string.Format(@"EXEC prDailyRouteReport 
                                 {0}",refId);

    using (var reader = command.ExecuteReader())
    {
       //reading data and fetch next result
    }
    connection.Close()
}

Now the issue is, when I need to call two separate reports within a single web request the connection variable returns empty connection string on the second report. but I didn't get the issue if I remove the using block. I want to know why im getting empty connection string with using statement.

1
  • Do you really need EF for this? Can you just open SqlConnection and do good old SqlCommand? Commented Jul 26, 2019 at 14:00

2 Answers 2

1

The using statement in c# can only be called when instantiating an object that implements the IDisposable interface, which means that the resultant instance can be disposed. This is what happens when code execution leaves the closing bracket of the using code block. The object instantiated within the using statement, in this case your connection variable, gets disposed, and any existing variable references will by trying to access a null reference unless it is reinstantiated first.

Additionally, you seem to be running into a threading issue where you are trying to perform operations on the same variable in different threads. The issue you are seeing is just a symptom of that. You need to address accessing your variables in multiple threads and you won't have this issue.

Sign up to request clarification or add additional context in comments.

Comments

0

This is beacause the connection is available only within the scope of the using. Just run the second report inside the using.

using (var connection = mydbcontext.Database.Connection)
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = string.Format(@"EXEC prDailyRouteReport 
                                 {0}",refId);

    using (var reader = command.ExecuteReader())
    {
       //reading data and fetch next result
    }

    command = connection.CreateCommand();
    command.CommandText = string.Format(@"EXEC prDailyRouteReport2 
                                 {0}",refId);

    using (var reader = command.ExecuteReader())
    {
       //reading data and fetch next result
    }

    connection.Close()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.