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.
ArticleServerContext
shares a sql connection? I'm assuming it's a static class – HalfhardyArticleServerContext
is my automatically generated DbContext class. – DecadeArticleServerContext.Database
class. I'm guessing it's caching those parameters. Try commenting out the countQuery line and use dummy data for it's results. – CentennialcountQuery
and the error persists. The assumption was that this would stop the error and that helps explain why I couldn't find a solution before. But it still makes even less sense now. – Decade