Insert using a Sequence as generator for a Primary Key value in Entity Framework

房东的猫 提交于 2019-12-10 18:24:48

问题


I have a sequence that looks like this:

CREATE SEQUENCE dbo.NextWidgetId
 AS [bigint]
 START WITH 100
 INCREMENT BY 2
 NO CACHE 
GO

And a table that looks like this:

CREATE TABLE [dbo].[Widget_Sequenced]
(
    [WidgetId] [int] NOT NULL DEFAULT(NEXT VALUE FOR dbo.NextWidgetId),
    [WidgetCost] [money] NOT NULL,
    [WidgetName] [varchar](50) NOT NULL,
    [WidgetCode] [int] NOT NULL,
    [LastChangedBy] [int] NOT NULL,
    [RowVersionId] [timestamp] NOT NULL,

    CONSTRAINT [PK_Widget_Sequenced] 
    PRIMARY KEY CLUSTERED ([WidgetId] ASC) ON [PRIMARY]
) ON [PRIMARY]

Is there a way to add a new record to this table structure using Entity Framework?

I tried setting StoreGeneratedPattern for WidgetId to computed and I tried it with Identity. Both gave me errors.

I tried this with EF 5. But I could move to EF 6 if it fixes this.


回答1:


It's possible from version 6.2, using this code:

System.Data.Entity.SqlServer.SqlProviderServices.UseScopeIdentity = false;

More information on EF6 does not work with primary key from sequence




回答2:


You can replace your sequence with IDENTITY(100, 2) and everything will work out of the box.



来源:https://stackoverflow.com/questions/30991993/insert-using-a-sequence-as-generator-for-a-primary-key-value-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!