Skip to content Skip to sidebar Skip to footer

Linq Inserts Without Identity Column

I'm using LINQ, but my database tables do not have an IDENTITY column (although they are using a surrogate Primary Key ID column) Can this work? To get the identity values for a

Solution 1:

Sure you can make this work with LINQ, and safely, too:

  • wrap the access to the underlying SystemValues table in the "GetIDValue.....()" function in a TRANSACTION (and not with the READUNCOMMITTED isolation level!), then one and only one user can access that table at any given time and you should be able to safely distribute ID's
  • call that stored proc from LINQ just before saving your entity and store the ID if you're dealing with a new entity (if the ID hasn't been set yet)
  • store your entity in the database

That should work - not sure if it's any faster and any more efficient than letting the database handle the work - but it should work - and safely.

Marc

UPDATE:

Something like this (adapt to your needs) will work safely:

CREATEPROCEDURE dbo.GetNextTableID(@TableIDINT OUTPUT)
ASBEGINSET TRANSACTION ISOLATION LEVEL READ COMMITTED

    BEGIN TRANSACTION 

    UPDATE SystemTables
    SET MaxTableID = MaxTableID +1WHERE ........ 

    SELECT@TableID= MaxTableID 
    FROM    
        dbo.SystemTables

    COMMIT TRANSACTION
END

As for performance - as long as you have a reasonable number (less than 50 maybe) of concurrent users, and as long as this SystemTables tables isn't used for much else, then it should perform OK.

Solution 2:

You are very justified in your concern. If two users try to insert at the sametime, both might be given the same number unless you do as described by marc_s and put the thing in a transaction. However, if the transaction doesn't wrap around your whole insert as well as the table that contains the id values, you may still have gaps if the outer insert fails (It got a value but then for some other reason didn't insert a record). Since most people do this to avoid gaps (something that is in most cases an unnecessary requirement) it makes life more complicated and still may not achieve the result. Using an identity field is almost always a better choice.

Post a Comment for "Linq Inserts Without Identity Column"