【问题标题】:Entity Framework: 'The SqlParameter is already contained by another SqlParameterCollection'实体框架:“SqlParameter 已包含在另一个 SqlParameterCollection 中”
【发布时间】:2014-04-18 11:33:03
【问题描述】:

我正在尝试执行以下代码。我的目标是检查是否存在具有给定电子邮件 ID 的用户。

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

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

但我在result.count() 遇到异常,不知道出了什么问题。

例外是:

"SqlParameter 已经被另一个包含 SqlParameterCollection"

我该如何解决这个问题?

【问题讨论】:

  • 你不能参数化你的列名,你可以参数化你的值。

标签: c# asp.net-mvc-4


【解决方案1】:

只需要在Sql查询后面加上ToList()方法,去掉SqlParameter中的@即可:

var result = userDbContext.users.SqlQuery("SELECT * FROM USERS WHERE 
@email=@emailValue",
new SqlParameter("email", "email"),
new SqlParameter("emailValue","abc@mail.com")).ToList();
//new SqlParameter("p1", existingUser.password));

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

它会起作用的。

【讨论】:

  • 这是其他有同样问题的人最有可能的答案。我用一个存储的过程和一个参数调用 SqlQuery 。不断收到同样的错误,并花了很长时间试图解决它。将 ToList 添加到我的声明的末尾,瞧 - 问题已解决。
【解决方案2】:

当您通过查询使用参数时,您不能在另一个查询中使用它们。在您的代码中,您使用它们两次

1- userDbContext.users.SqlQuery....
2- result.Count().

但是如果你使用这个代码:

"userDbContext.users.SqlQuery(...).Count()" 

您的代码将是正确的

** SqlQuery 不会返回查询结果,直到您使用像 any()、tolist() 这样的 linq 扩展......另一方面,当您使用 SqlQuery 时,结果是一个 IEnumerable 当您使用 any( ), tolist(), first() 转换成结果

【讨论】:

  • @Theresa:谢谢你,theresa。但是你能告诉我为什么我的回答被否定了吗?
【解决方案3】:

做这样的事情:

SqlParameter parameter = new SqlParameter("email", SqlDbType.VarChar);
parameter.Value = "test@yahoo.com";

或者试试这样:

var check =userDbContext.Database
           .SqlQuery<user>("SELECT * FROM USERS 
                           WHERE email=@emailValue", 
                           new SqlParameter("@emailValue","abc@mail.com")).ToList();

SqlParameter 是这样的:

var p = new SqlParameter {
    ParameterName = "paramName",
    DbType = DbType.Bit,
    Direction = ParameterDirection.Output
};

【讨论】:

    【解决方案4】:

    在末尾粘贴 .ToList() 并在此位置执行查询。在 ToList 之前对原始查询的任何后续调用都会引发此错误,但如果您使用 ToList 结果,则它将正常工作。

    我遇到了同样的问题,因为我使用了运行查询的 Any(),然后在没有 ToList 的情况下针对查询运行 First()。它尝试再次运行查询,但它已经运行,因此已经定义了这些参数。所以总而言之,在最后拍一下 ToList 并使用该结果对象,因为您不想再次执行 SQL 查询。

    【讨论】:

      【解决方案5】:

      你可以试试这个

      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();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-17
        • 1970-01-01
        • 1970-01-01
        • 2011-12-11
        • 2011-09-11
        • 2019-04-10
        • 2012-06-14
        相关资源
        最近更新 更多