简体   繁体   English

LINQPad:如何使用SQLite整数主键自动分配

[英]LINQPad: How to use SQLite integer primary key automatic assignment

In SQLite: 在SQLite中:

If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID. 如果表包含INTEGER PRIMARY KEY类型的列,则该列将成为ROWID的别名。

When a new row is inserted into an SQLite table, the ROWID can either be specified as part of the INSERT statement or it can be assigned automatically by the database engine. 当在SQLite表中插入新行时,可以将ROWID指定为INSERT语句的一部分,也可以由数据库引擎自动分配它。

If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically. 如果在插入上未指定ROWID,或者指定的ROWID的值为NULL,则将自动创建适当的ROWID。

I created a table in SQLite with an integer primary key, and then opened the file in LINQPad. 我在SQLite中用整数主键创建了一个表,然后在LINQPad中打开了该文件。 I'm trying to insert a new row into the table via C#: 我正在尝试通过C#将新行插入表中:

var episode = new RateableItem()
{
    SourceId = "tal",
    Edition = episodeNum.ToString(),
    Name = episodeName,
    Consumed = false
};

RateableItems.InsertOnSubmit(episode);
SubmitChanges();

In the above example, I haven't specified the pimary key. 在上面的示例中,我没有指定pimary键。 This fails because LINQPad has mapped the primary key to a non-nullable int, so the generated SQL inserts a 0 into the primary key, which fails because a row with PK 0 already exists. 失败是因为LINQPad已将主键映射到不可为null的int,所以生成的SQL会在主键中插入0,而失败是因为已存在PK 0的行。

Is there a way to configure LINQPad with SQLite so that it passes a null for the PK, allowing SQLite to automatically assign the PK value? 有没有一种方法可以使用SQLite配置LINQPad,以便它为PK传递一个空值,从而允许SQLite自动分配PK值?

Thanks to the sample database that @sgmoore posted in comments, I was able to find that declaring the table primary key as AUTOINCREMENT solves my issue. 感谢@sgmoore在评论中发布的示例数据库,我发现将表主键声明为AUTOINCREMENT可以解决我的问题。

CREATE TABLE RateableItem (
  RateableItemId INTEGER PRIMARY KEY AUTOINCREMENT,
  SourceId NVARCHAR(32) NOT NULL,
  Name NVARCHAR(255),
  Edition NVARCHAR(16),
  Consumed BOOLEAN NOT NULL
);

When I added AUTOINCREMENT to my table definition, I was able to create a new object without specifying the key. 当我将AUTOINCREMENT添加到表定义中时,无需指定键就可以创建新对象。 LINQPad's Schema Explorer doesn't show any difference between a primay key with AUTOINCREMENT versus without, but my script compiles and SQLite assigns a value on SubmitChanges() . LINQPad的Schema Explorer在具有AUTOINCREMENT的主键和没有AUTOINCREMENT的主键之间没有显示任何区别,但是我的脚本可以编译,并且SQLite在SubmitChanges()上分配一个值。

There are some differences in primary key behavior with AUTOINCREMENT. AUTOINCREMENT在主键行为上有一些差异。 Fortunately these are fine in my scenario. 幸运的是,在我的情况下这些都很好。

 var episode = new RateableItem()
 {
     PrimaryKey = null,
     SourceId = "tal",
     Edition = episodeNum.ToString(),
     Name = episodeName,
     Consumed = false
 };

How does that work? 这是如何运作的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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