简体   繁体   中英

SQLite.Net SQLiteException Constraint

I've looked here before with this error but the results won't work for me.

I have made a login form and it works fine for one time. After I logged in once and restart the app and try to log in I'm getting the error.

Function:

public int SaveUser(User user)
{
    lock (locker)
    {
        if (user.Id != 0)
        {
            database.Update(user);
            return user.Id;
        }

        else
        {
            return database.Insert(user);
        }
    }
}

User model:

[Table("User")]
public class User
{   
    [PrimaryKey, AutoIncrement, NotNull]
    public int Id { get; set; }
    [Unique]
    public string Username { get; set; }
    public string Password { get; set; }
}

Update: I hope this are the details that's needed for further help.

02-27 14:13:15.806 I/MonoDroid(23447): at SQLite.PreparedSqlLiteInsertCommand.ExecuteNonQuery (System.Object[] source) [0x00121] in /Users/vagrant/git/src/SQLite.cs:2668 02-27 14:13:15.806 I/MonoDroid(23447): at SQLite.SQLiteConnection.Insert (System.Object obj, System.String extra, System.Type objType) [0x000f4] in /Users/vagrant/git/src/SQLite.cs:1415 02-27 14:13:15.806 I/MonoDroid(23447): at SQLite.SQLiteConnection.Insert (System.Object obj) [0x00005] in /Users/vagrant/git/src/SQLite.cs:1281 02-27 14:13:15.806 I/MonoDroid(23447): at KleynGroup.Data.UserDatabaseController.SaveUser (KleynGroup.User user) [0x00038] in C:\\Users\\[name]\\source\\repos\\KleynGroup\\KleynGroup\\KleynGroup\\Data\\UserDatabaseController.cs:48

Sorry if there are a lot of mistakes. I'm new to Xamarin and still learning.

I hope you guys can help me

According to the error messages the exception is thrown by Insert , hence I'd assume that you are trying to insert the User ( User.Id seems to be 0 ). Anyway, since it's not a new, but an existing user name, inserting it fails because of the UNIQUE constraint of Username .

You have to make sure, that when the user is loaded and then saved, it still has the correct ID, to prevent that exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM