我正在尝试将一些数据插入到我的SQLite数据库中,当我使用一条记录执行此操作时,该数据库非常有效。但在循环中我得到一个错误。首先,这是代码
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();
}
用户本身
[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; }
}
表格就是这样创建的
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
)
最后我得到了错误:
System.Data.Linq.dll中出现'System.Data.Linq.DuplicateKeyException'类型的异常,但未在用户代码中处理
其他信息:EineEntität,derenSchlüsselbereitsverwendet wird,kannnichthinzugefügtwerden。
我敢打赌,由于字段ID
设置为AutoIncrement
,这种情况正在发生。
答案 0 :(得分:0)
你只需删除ID = null,因为这是自动增量而不需要写这个。 更改表&#34;用户&#34;删除NOT NULL检查自动增加列ID,并在类&#34; User&#34;中删除。 ID列是自动递增,然后不需要使用NOT NULL约束进行检查。
for (int i = 0; i < 2; i++) {
User tempUser = new User() {
EMail = i + "@" + i + ".de",
Password = "Test1234",
JoinedDate = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss")
};
答案 1 :(得分:0)
假设您的代码在一次插入时工作正常,我会尝试其中一种解决方案
解决方案1
在循环之外调用context.SubmitChanges();
所以
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();
解决方案2
使用InsertAllOnSubmit
var tempUsers = Enumerable.Range(0, 2)
.Select(i => new User{
ID = null,
EMail = i + "@" + i + ".de",
Password = "Test1234",
JoinedDate = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss")
});
users.InsertAllOnSubmit(tempUsers);
context.SubmitChanges();
解决方案3
在每个循环中处理并重新创建上下文(似乎是一个相当糟糕的主意)
for (int i = 0; i < 2; i++) {
using (var context = new DataContext(Connection)) {
var users = context.GetTable<User>();
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();
}
}