1

I have this code in a method

string _errorMessage = string.Empty;

SqlParameter[] @params = {
    new System.Data.SqlClient.SqlParameter("@id", entity.Id),
    new System.Data.SqlClient.SqlParameter("@userId", _user.SecUserId),
    new System.Data.SqlClient.SqlParameter("@lockProcess", "Bulk Receipting For Employer"),
    new System.Data.SqlClient.SqlParameter("@errorMessage", SqlDbType.VarChar, 200) {Direction = ParameterDirection.Output}
};

var reader = _context.Database.ExecuteSqlCommand("usp_LockAndReadCase @id, @userId, @lockProcess, @errorMessage OUTPUT", @params);
_errorMessage = @params[3].Value.ToString();
return _errorMessage;

In one particular area, I call this method in a loop for where I have multiple Ids to pass. When it's called consecutively, I get the error:

System.InvalidOperationException: 'There is already an open DataReader associated with this Command which must be closed first.'

Since I am using Entity Framework and ASP.NET Core, I am using the ExecuteSqlCommand and have no need to create a SqlConnection or DataReader.

How do I resolve this issue?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nikki
  • 11
  • 1
  • 1
    Possible duplicate of [There is already an open DataReader associated with this Command which must be closed first](https://stackoverflow.com/questions/6062192/there-is-already-an-open-datareader-associated-with-this-command-which-must-be-c) – Dave Cousineau Sep 30 '19 at 15:52
  • This is not a duplicate issue. None of those answers resolve my issue. The issue I explained is not a problem when enumerated query results, its a legit database call using the _context.Database syntax. I assume that the Database is opening a call to the database, but I do not have access to that connection to close it. Is there another way to achieve the same results here or what should I change to resolve this issue? I am fairly new to asp and entityframework. Thanks. – Nikki Sep 30 '19 at 17:48
  • @Nikki you most likely need to enable Multiple Active Result Sets (MARS) as per the other question. are you saying that you've enabled MARS but still get this error? (Or maybe that you want to do what you're doing without enabling MARS?) – Dave Cousineau Sep 30 '19 at 18:08
  • You were correct Dave, I added the MARS and am no longer receiving the error. I thought there might have been another way to handle this issue or that maybe I was doing something incorrectly. Thanks for the help! – Nikki Oct 01 '19 at 12:24

0 Answers0