Search code examples
c#asp.net-mvc-4

Entity Framework: 'The SqlParameter is already contained by another SqlParameterCollection'


I am trying to execute below code. My goal is to check whether any user exists with the given email id or not.

var result = userDbContext.users.SqlQuery("SELECT * FROM USERS WHERE @email='@emailValue'",
new SqlParameter("@email", "email"),
new SqlParameter("@emailValue","[email protected]"));
//new SqlParameter("p1", existingUser.password));

if (result.Count() == 0) //getting exception here
{
    ViewBag.comment = "Sorry. We can not find your credentials";
    return View();
}

But I am getting exception at result.count() and don't know what is going wrong.

Exception is:

"The SqlParameter is already contained by another SqlParameterCollection"

How can I solve this?


Solution

  • You can try this

    var check = (from item in userDbContext.users where item.email == email select item).FirstOrDefault();
    if (check == null)
    {
        ViewBag.comment = "Sorry. We can not find your credentials";
        return View();
    }