2014-04-18 70 views
4

我想執行下面的代碼。我的目標是檢查是否存在具有給定電子郵件ID的用戶。實體框架:'SqlParameter已經包含另一個SqlParameterCollection'

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

但我在result.count()越來越異常,不知道什麼錯誤。

的例外是:

我該如何解決這個 「SqlParameter有已被另一 SqlParameterCollection載」?

+4

你不能參數你的列名,你可以參數你的值。 –

回答

0

你可以試試這個

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

做這樣的事情:

SqlParameter parameter = new SqlParameter("email", SqlDbType.VarChar); 
parameter.Value = "[email protected]"; 

或嘗試這樣的:

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

的SqlParameter是這樣的:

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

當您通過查詢使用參數時,不能通過其他查詢使用它們。在你的代碼使用的是他們的兩倍

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

,但如果您使用此代碼:

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

您的代碼將是正確的

**類SqlQuery不直到您使用返回的查詢結果(),tolist()......另一方面,當你使用SqlQuery時,當你使用any(),tolist(),first()時,結果是一個IEnumerable它被轉換爲結果

+0

@Theresa:謝謝你,theresa。但你能告訴我爲什麼我的答案得到了否定的答覆。 – amin

相關問題