Jam*_*mer 7 sql entity-framework sql-server-2012-express
我以前从未见过这种情况,很奇怪.
我有一个本地SQL Server 2012 Express数据库,我正在开发.使用TestDrive插件运行一组简单的测试,并使用EF v5访问数据库.
我刚刚运行了一个将记录插入数据库的测试.我从表1-9开始在表中有9行.下一个插入和ID正好跳了10000 !!!!
Id列为:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10009
Run Code Online (Sandbox Code Playgroud)
我知道失败的插入也会增加ID,但我可以保证在测试运行之间的5秒内没有插入10,000个...
表结构非常简单,一堆列和一个自动递增,类型bigint(长)的标识列,没有SP,触发器或任何其他程序化内容.
[Id] [bigint] IDENTITY(1,1) NOT NULL,
Run Code Online (Sandbox Code Playgroud)
很混乱,还有其他人看到过这种情况吗?
这篇博文有一些额外的细节。看起来像2012年,identity是作为一个序列实现的。默认情况下,序列有一个缓存。如果缓存丢失,您将丢失缓存中的序列值。
建议的解决方案是创建一个序列no cache:
CREATE SEQUENCE TEST_Sequence
AS INT
START WITH 1
INCREMENT BY 1
NO CACHE
Run Code Online (Sandbox Code Playgroud)
据我所知,身份列后面的序列是不可见的。您无法更改其属性来禁用缓存。
要将其与实体框架一起使用,您可以将主键设置StoredGeneratedPattern为Computed。然后您可以在触发器中生成身份服务器端instead of insert:
if exists (select * from sys.sequences where name = 'Sequence1')
drop sequence Sequence1
if exists (select * from sys.tables where name = 'Table1')
drop table Table1
if exists (select * from sys.triggers where name = 'Trigger1')
drop trigger Trigger1
go
create sequence Sequence1
as int
start with 1
increment by 1
no cache
go
create table Table1
(
id int primary key,
col1 varchar(50)
)
go
create trigger Trigger1
on Table1
instead of insert
as
insert Table1
(ID, col1)
select next value for Sequence1
, col1
from inserted
go
insert Table1 (col1) values ('row1');
insert Table1 (col1) values ('row2');
insert Table1 (col1) values ('row3');
select *
from Table1
Run Code Online (Sandbox Code Playgroud)
如果您找到更好的解决方案,请告诉我:)