Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlParameter is already contained by another SqlParameterCollection, but I don't see how

I have the following code.

// Get total row count and build Pagination object
var countQuery = ArticleServerContext.Database.SqlQuery<int>("GetFullTextSearchCount @SearchTerm",
    new SqlParameter("@SearchTerm", fullTextQuery));
Pagination pagination = new Pagination(countQuery.Single(), page ?? 1);
// Get search results for current page
var resultsQuery = ArticleServerContext.Database.SqlQuery<ArticleSummary>("GetFullTextSearchResults @SearchTerm, @SkipRows, @TakeRows",
    new SqlParameter("@SearchTerm", fullTextQuery),
    new SqlParameter("@SkipRows", pagination.SkippedRows),
    new SqlParameter("@TakeRows", pagination.RowsPerPage));
// Build model
SearchResultsModel model = new SearchResultsModel
{
    SearchTerm = searchTerm.Trim(),
    Pagination = pagination,
    Results = resultsQuery.ToList()   // <=== Here's where the error happens
};

When I attempt to enumerate resultsQuery, I get the following error message.

The SqlParameter is already contained by another SqlParameterCollection.

This error message seems clear enough, but I cannot see where I'm adding an SqlParameter to more than one anything. The only thing I can imagine is that the first parameter to both calls are identical. Could C# be combining them somehow? Either way, I need them to contain the same data.

Can anyone see what's happening here?

EDIT:

Sorry, this turned out to be a debugging issue. I had another issue that prevented the results I expected. But when I break in the debugger and step through my code, I get the error mentioned above.

It seems that the code executes using the SqlParameter in question, and then I attempt to inspect the contents of the query and the query runs again with the same SqlParameter, and that is what is causing the error.

Unfortunately, now that I have a bounty, I cannot delete the question.

like image 755
Jonathan Wood Avatar asked Jun 19 '16 21:06

Jonathan Wood


1 Answers

I didn't have a good understanding of what was happening when I posted this question. After further study, it turns out that:

  1. A separate issue was causing my program not to display the (any) results I expected.

  2. Using the Visual Studio debugger, I had set a breakpoint in this code. As I stepped through, the queries were being executed. But then when I attempt to inspect the data, that caused the queries to be executed again. It was this dual execution that was causing the error I reported. In fact, this error was not occurring when the code ran normally.

Thanks to everyone who took time to look at this issue.

like image 69
Jonathan Wood Avatar answered Oct 01 '22 00:10

Jonathan Wood