ef6 mysql 获取自增id,EF6:如何根据实体ID自动生成唯一编号

本文讨论了在数据库中为`Document`类生成唯一`code`字段的挑战,传统的递增方法存在安全性问题。提出了规范化表格,创建`DocumentCodes`表以分离`code`字段,并使用种子值初始化的解决方案。还提到了使用事务确保安全性以及考虑将`code`作为计算属性的替代方案。此外,建议根据日期和`Id`生成`code`,并在创建`Document`实体前先生成`DocumentCodes`记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Consider an entity like this:

public class Document

{

public int Id { get; set; }

public long code { get; set; }

// Rest of Props

}

What I need is to generate a unique long code, and I prefer to generate it based on Id.

One simple classic but unsafe solution is to get the last Id and increase it by one and use, but I'm looking for a better solution, such as computed column, or any other way to assign code generation to database.

I cannot access to Id if I try define it as a compute column.

Marking it as Identity is not possible, because Id is already an

Identity column.

Creating a method to Get the last Id is not safe and clean.

By now I'm trying to do former classic solution with the help of transactions to make it safe.

Any better suggestion?

解决方案

A workaround to the limitation of a single identity field per table would simply be to normalise the Documents table into a further table containing the code field and any related fields.

In order to get the base value (based on date) for the code identity field could simply be seeded with the lowest desired value. Don't know the underlying RDMS, but for MySQL it would be along the lines of http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html

So, something like

Documents 1-1 DocumentCodes

where:

DocumentCodes

-------------

code : identity (seeded to desired base value)

documentId : int FK UNIQUE

A further alternative to allow the code field to be generated separately (including before) the actual Document entity would be as follows:

DocumentCodes

-------------

code : identity PK

Documents

---------

id : identity

code : id FK

The actual code field could be seeded to the required base number, or used as part of a computed property as per my other answer.

Create an entity in the DocumentCodes table and get the generated code

Create a computed code for the end user based on the generated code and a number generated from the date

Create the Document entity, passing in the generated code

To search for a Document based on code:

Strip the date part off the computed code

Search in the Document table on code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值