Brian Mains
Brian Mains

Reputation: 50728

A parameter named 'p__linq__0' already exists in the parameter collection. Parameter names must be unique in the parameter collection

This is a strange error I'm getting from Entity Framework: "A parameter named 'p_linq_0' already exists in the parameter collection. Parameter names must be unique in the parameter collection." I am not doing any custom parameters or anything fancy, simply straight LINQ queries or stored procedure executions, nothing fancy, nothing out of the ordinary, no Entity SQL... so why would this error happen?

Thanks.

Upvotes: 4

Views: 2942

Answers (2)

Krenom
Krenom

Reputation: 2118

I had the same issue - I was running several queries in parallel in their own Task.Runs.

Each of my queries used a list of Ids that I was populating with var ids = _someList.Select(x => x.Thing.Id).Distinct()

Constructing the parameters of the multiple queries, I was doing string.Join(",", ids) in several of them.

The answer eventually became apparent: deferred execution.

Each query, at the point where it was doing string.Join(",", ids), finally executed the query for the ids (at the same time) causing the duplicate parameter (p_linq_0).

Simply adding .ToList() to execute on that line meant the queries had a concrete list of Ids to use and weren't all trying to do it at the same time themselves.

var ids = _someList.Select(x => x.Thing.Id).Distinct().ToList();

Upvotes: 3

Andrew
Andrew

Reputation: 5176

Without seeing your code, we can't possibly figure out what your problem is. It sounds like there are a few things that could cause this. I seem to have discovered one, though. I have a model whose primary key is an enum, so I was doing this:

context.Tests.Where(t => t.TypeId == TestTypeId.SingleTimeWholeClass)

Inexplicably, casting each side of the comparison to an int fixed my problem:

context.Tests.Where(t => (int)t.TypeId == (int)TestTypeId.SingleTimeWholeClass)

Could be totally unrelated to your problem. Posting code always helps.

Upvotes: 0

Related Questions