I am trying to use a custom identity column in a table using Entity Framework. What I have is a table used to control the next available Id to use for each table.
CREATE TABLE [dbo].[SystemNumbers](
[SystemNumberDesc] [varchar](30) NOT NULL,
[LastId] [Int] NOT NULL
CONSTRAINT [PK__SystemNumbers] PRIMARY KEY CLUSTERED
(
[SystemNumberDesc] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
with a row containing a row counter for the table, inserted as follows
INSERT INTO SystemNumbers VALUES ('WS', 0)
I then create the table that I want to use
CREATE TABLE [dbo].[WS](
[WorkstationID] INT NOT NULL,
[WorkstationName] [varchar](50) NULL,
[WSTS] TIMESTAMP,
CONSTRAINT [PK_WS] PRIMARY KEY CLUSTERED
(
[WorkstationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
and then create the trigger to get the next Id from the SystemCounters
table and update the ID as follows
CREATE TRIGGER WSId
ON WS AFTER INSERT
AS BEGIN
DECLARE @LastId INT
DECLARE @TableName VARCHAR(100)
DECLARE @INSERTID INT
SET @TableName = 'WS'
SET NOCOUNT ON
SELECT @INSERTID = SystemID, @CREATETS = SystemTS, @StoreId = StoreId FROM Inserted
IF (@INSERTID = 0) BEGIN
SELECT @LastId = LastId + 1 FROM SystemNumbers WHERE SystemNumberDesc = @TableName
UPDATE SystemNumbers SET LastId = @LastId WHERE SystemNumberDesc = @TableName
UPDATE WS SET SystemId = @LastId, WorkstationID=@LastId WHERE SystemId = @INSERTID
END
END
GO
This works fine using SQL to perform the insert. I then add an ADO.Net Entity Framework to my project and attempt to insert a record.
This give me the initial problem that the column is defined as Computed and needs to be changed to Identity. I change this and then get
An unhandled exception of type 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll
Additional information: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
I suspect this is because it inserts the record and then attempts to reload it to get the Db values such as the Timestamp.
I have followed a number of thread but just ended up in a circle. I need to set the column from the table as it is multi-store and so an Identity field will not work.