I have a database table Contact
, in my application layer I'm getting a request from the client (i.e., Web API HTTP request) and I'm pushing the data into MSMQ.
I also have a Windows Service which receives the message from the respective MSMQ and processes the data. It inserts the data into the respective database table Contact
.
SQL Server table structure of Contact
:
CREATE TABLE [dbo].[Contact]
(
[ContactId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[Email] [varchar](255) NOT NULL,
[Mobile] [varchar](10),
[CreatedDate] [datetime2](7) NOT NULL,
CONSTRAINT PK_Contact PRIMARY KEY (ContactId)
)
In this process, I need to send the primary key of the table Contact
because the primary key is the Id
of Contact
. In the response, the client expects the Contact Id
.
It is possible to allot an Id
of Contact
before data is inserted? or kindly assist me.
Please let me know changes required in the table structure.
If you want to know which will be the next identity value, there is a built-in function for that. Nevertheless doing what you are suppposed to do is not recomended because other sessions may insert in that table. You may want to use other method of creating a numeric ID for your table, or just insert some data to "allot" and the updating with your real values. It seems a lot of work and I would recomend to insert the data and then getting the real ID with SCOPE_IDENTITY() function. That would be much secure.
Anyway, here is the function that will return that next autonumeric value: