C#用LINQ麻烦更新记录

时间:2011-03-20 15:14:41

标签: c# linq

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

在线

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\

有人能告诉我如何在记录中更新此计数器吗?

2 个答案:

答案 0 :(得分:5)

如果要编辑它,只需选择整个用户项。摆脱整个“选择新”条款。

答案 1 :(得分:2)

您无法更新匿名类实例的属性(即使您可能只是本地更改并且与DB中的任何用户实体无关,因为匿名类实例是一个新的,不同的对象,您是投影到),你必须选择要更新的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();