I am trying to insert some data into my SQLite database which works perfectly when I do this with one record. But inside a loop I get an Error. First, here is the code
string dataSource = "Data Source=";
Connection = new SQLiteConnection(dataSource + this.DatabasePath);
var context = new DataContext(Connection);
var users = context.GetTable<User>();
for (int i = 0; i < 2; i++) {
User tempUser = new User() {
ID = null,
EMail = i + "@" + i + ".de",
Password = "Test1234",
JoinedDate = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss")
};
users.InsertOnSubmit(tempUser);
context.SubmitChanges();
}
And the User itself
[Table(Name = "User")]
public class User {
[Column(Name = "UserID", IsPrimaryKey = true, CanBeNull = false)]
public int? ID { get; set; }
[Column(Name = "EMail", CanBeNull = false)]
public string EMail { get; set; }
[Column(Name = "Password", CanBeNull = false)]
public string Password { get; set; }
[Column(Name = "JoinedDate", CanBeNull = false)]
public String JoinedDate { get; set; }
[Column(Name = "PaymentMethodID")]
public int PaymentMethodID { get; set; }
}
The Table is created like this
CREATE TABLE "User" (
`UserID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`EMail` TEXT NOT NULL,
`Password` TEXT NOT NULL,
`JoinedDate` TEXT NOT NULL,
`Licenses` INTEGER,
`PaymentMethodID` INTEGER
)
And finally the Error I get:
An exception of type 'System.Data.Linq.DuplicateKeyException' occurred in System.Data.Linq.dll but was not handled in user code
Additional information: Eine Entität, deren Schlüssel bereits verwendet wird, kann nicht hinzugefügt werden.
I could bet, that this is happening because of the Field ID
, which is set to AutoIncrement
.