我有以下实体
[Table(Name = "Users")]
public sealed class UserDB
{
private Int64 _id = -1;
private string _username = string.Empty;
public UserDB() { }
public UserDB(RepositoryInfo repoInfo)
{
UserName = repoInfo.Account;
}
[Column(Name = "ID", Storage = "_id", IsDbGenerated = true, IsPrimaryKey = true, UpdateCheck = UpdateCheck.Never)]
public Int64 ID { get { return _id; } set { _id = value; } }
[Column(Name = "UserName", DbType="nvarchar(50)", Storage = "_username")]
public string UserName { get { return _username; } set { _username = value; } }
}
ID 映射到自动增量INTEGER类型列(实际上是SQLite中自动增量可能的唯一类型)
当我尝试像这样向DB添加新用户时,出现错误:
public static Int64 AddUser(DataContext context, RepositoryInfo repoInfo)
{
UserDB udb = new UserDB(repoInfo);
//an ID of udb is -1, but I tried different values too, doesn't change result
var userstable = context.GetTable<UserDB>();
userstable.InsertOnSubmit( udb );
context.SubmitChanges(); // here I get a error, see on screen shot
return udb.ID;
}
修改
在谷歌搜索和检查后,似乎SQLite根本不提供任何SCOPE_IDENTITY()
功能。但是Linq To SQL注入了它!
我该如何更改?
答案 0 :(得分:3)
实际上,我找不到解决此问题的解决方案,如果不是那个架构的那个=&gt;更改linq查询以更改输出的SQL。
答案 1 :(得分:0)
这似乎有点hacky但是根据this answer你只需要将“null”传递给你的id列,以便sqlite执行自动增量。这对我有用:
[Table(Name = "yourtable")]
class yourclass
{
[Column(Name = "id", IsPrimaryKey=true )]
public int? Id { get; set; }
...
然后,当您为InsertOnSubmit创建一个新对象时,您可以省略id列,它将默认为null。
要获取使用自动增量创建的新ID,请参阅here