using System.Linq; namespace Product.Host { public class HiLoGenerator { private const int HiLoIncrement = 10; private int _sequenceId = -1; private int _remainningLoIds = 0; private object SequenceLock = new object(); public int GetNextSequenceValue(ProductDbContext db) { lock (SequenceLock) { if (_remainningLoIds == 0) { var rawQuery = db.Database.SqlQuery<long>("SELECT NEXT VALUE FOR Product_HiLo;"); _sequenceId = (int)rawQuery.Single(); _remainningLoIds = HiLoIncrement - 1; return _sequenceId; } else { _remainningLoIds--; return ++_sequenceId; } } } } }
sql
CREATE SEQUENCE [dbo].[Product_HiLo] AS [bigint] START WITH 1 INCREMENT BY 10 MINVALUE -9223372036854775808 MAXVALUE 9223372036854775807 CACHE