8

I have the following that is throwing a The SqlParameter is already contained by another SqlParameterCollection exception in the catch block.

What I find odd is that nowhere do we create a SqlParameterCollection. Each time we create a new instance so the SqlParameter is never used more than once. And another oddity is that test contains the correct results from the stored procedure and returns the results to the calling method, but when I step one more time from line 3 to 4 is when it decides to enter the catch block. Not at line 33 where I would expect it to occur... If it helps any we switched from an ObjectContext to a DbContext using the CodeFirst generation tools. All other database interactions and stored procedures used are working as expected.

1    try
2    {
3        tempMessages = Context.CheckExistingTables(importSession.ImportSessionID).ToList();
4    }
5    catch (Exception e)
6    {
7        this.LogError("Error validating the import file entities", e);
8        tempMessages.Add(new ErrorMessage() { ErrorType = 3, Message = string.Format("Error validating the import file entities: {0}", e.Message) });
9    }
...
20    public IEnumerable<ErrorMessage> CheckExistingTables(Guid? importSessionID)
21    {
22        SqlParameter importSessionIDParameter;
23
24        if (importSessionID.HasValue)
25        {
26            importSessionIDParameter = new SqlParameter("importSessionID", importSessionID);
27        }
28        else
29        {
30            importSessionIDParameter = new SqlParameter("importSessionID", typeof(System.Guid));
31        }
32
33        var test = Database.SqlQuery<ErrorMessage>("Import.CheckExistingTables @importSessionID", importSessionIDParameter);
34        return test;
35    }

1 Answer 1

19

So somehow the answer was to call .ToList() at the end of line 33.

Note to others... Add the using statment using System.Linq; to the top of your file or you won't have the ToList() option.

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

1 Comment

Thank you very much a quick and easy solution to the issue I was experiencing!

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.