我有一个简单的应用程序,必须为创建的每个Document
分配一个连续的数字
,没有间隙或重复,即1、2、3等。不同的文档类型将具有不同的编号顺序。
DocumentTypes
是一个数据库表,存储不同类型的文档,例如书籍、食谱、白皮书
Documents
是一个数据库表,存储文档信息,包括其顺序ID
数据库关系是一个
DocumentType
可以有多个 Documents
但每个 Document
只能有一个 DocumentType
如果
DocumentType.LastNumber
保存为特定文档类型分配的最后一个编号,我的计划是:
// create a transaction to lock the DocumentType row being assigned so no duplicates
var transaction = dbContext.Database.BeginTransaction(IsolationLevel.Serializable);
// get the appropriate document type from the db
var documentType = dbContext.DocumentTypes.Single(t => t.Id == 1);
// increment the last document number
documentType.LastNumber++;
// create the new document with the new number
documentType.Documents.Add(new Document{
Id = documentType.LastNumber,
...
});
dbContext.SaveChanges();
// commit the transaction and release the db lock
transaction.Commit();
但是,我发现对于给定的文档类型,我得到了重复的数字(当我通过 API 异步调用此方法时)
我怀疑我误解了数据库事务和
IsolationLevel.Serializable
的工作原理。任何反馈将不胜感激。
如果是我的话
我不会有无间隙数字的东西......只是我的偏好。
但是,根据您的愿望,我会在文档表上创建一个触发器,以使用序列填充递增数字。