Alper
Alper

Reputation: 789

Concurrency logic in asp.net

I have a web form that inserts a row into an SQL Server 2008 table. Table has a field which must be unique, but for some reasons we are not allowed to use autoincrement utility. Instead of this I select the maximum of this field and increment it from code and insert the row with that id.

The problem is, if more than one person uses this form simultaneously, there occurs a concurrency problem and same id will be inserted to the table. I do not know how to solve this issue in a asp.net web project because all users have their own session and threads.

Any idea on how to manage concurrency problems in asp.net project will be very useful.

Thanks.

Upvotes: 2

Views: 120

Answers (1)

Tisho
Tisho

Reputation: 8492

If you perform the insert into a stored procedure, or in a transaction in the code, I don't see a reason to have problems with concurrency. Something like:

BEGIN TRAN
DECLARE @MAX int
SELECT @MAX = MAX(ID) FROM MyTable
INSERT INTO MyTable (@MAX, VAlue, Value2..)
COMMIT TRAN

or

SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
transaction = connection.BeginTransaction("InsertRow");

... perform insert using command object ...

transaction.Commit();

Upvotes: 1

Related Questions