2011-03-20 105 views
0
public static bool CheckLogin(string Username, string Password, bool AutoLogin) 
    { 
     bool LoginSuccessful; 

     // Trim inputs and verify lengths 
     Username = Username.Trim(); 
     Password = Password.Trim().ToLower(); 

     // Get the associated user records 
     DataClassesDataContext db = new DataClassesDataContext(); 
     var q = (from User in db.tblForumAuthors where User.Username == Username select new 
       { 
        User.Password, 
        User.Salt, 
        User.Username, 
        User.Author_ID, 
        User.User_code, 
        User.Active, 
        User.Login_attempt, 
        User.Last_visit, 
       }).SingleOrDefault(); 

     // Invalid details passed 
     if (q == null) 
     { 
      LoginSuccessful = false; 
     } 
     else 
     { 
      // Increment login attempts counter 
      int LoginAttempts = q.Login_attempt; 
      LoginAttempts++; 

      // Encrypt the password 
      string HashedPassword = GetSha1(Password + q.Salt); 

      // Check passwords match 
      if (q.Password == HashedPassword) 
      { 
       LoginSuccessful = true; 
      } 
      else 
      { 
       LoginSuccessful = false; 

       // Increment login attempts 
       q.Login_attempt = LoginAttempts; 
       db.SubmitChanges(); 
      } 
     } 
     return LoginSuccessful; 
    } 
} 

上線C#順利更新記錄與LINQ

q.Login_attempt = LoginAttempts; 

我得到:

Error 50 Property or indexer 'AnonymousType#1.Login_attempt' cannot be assigned to -- it is read only C:\inetpub\wwwroot\ScirraNew\App_Code\Login.cs 82 17 C:\...\ScirraNew\

誰能告訴我我怎麼能在記錄更新這個櫃檯嗎?

回答

5

如果你想編輯它,你只需要選擇整個用戶項目。擺脫你的整個「選擇新」子句。

2

您無法更新匿名類實例的屬性(即使您可以更改只是本地的,並且不與數據庫中的任何用戶實體相關,因爲匿名類實例是一個新的且不同的對象,您正在投影),您必須選擇User實體本身進行更新。

所以不是:

var q = (from User in db.tblForumAuthors 
      where User.Username == Username 
      select new 
      { 
       User.Password, 
       User.Salt, 
       User.Username, 
       User.Author_ID, 
       User.User_code, 
       User.Active, 
       User.Login_attempt, 
       User.Last_visit, 
      }).SingleOrDefault(); 

用途:

var q = (from User in db.tblForumAuthors where User.Username == Username select User).SingleOrDefault(); 

或者在lambda語法:

var user = db.tblForumAuthors.Where(u => u.UserName == UserName) 
       .SingleOrDefault(); 
+0

+1的λ/方法的語法(我討厭查詢語法) – jlnorsworthy 2011-03-22 07:08:22