EF6:如何根据实体ID自动生成唯一编号 [英] EF6: How to generate a unique number automatically based on entity Id

查看:1067
本文介绍了EF6:如何根据实体ID自动生成唯一编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个这样的实体:

 public class Document
 {

    public int Id { get; set; }

    public long code { get; set; }

    // Rest of Props

 }

我需要的是生成一个独特的长代码,我更喜欢根据Id生成它。

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

一个简单的经典但不安全的解决方案是获取最后一个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.


  • 如果我尝试将其定义为计算列,我无法访问Id。

  • 将其标识为身份是不可能的,因为Id已经是
    身份列。

  • 创建一个获取最后一个ID的方法是不安全和干净的。

到目前为止,我试图用交易的帮助进行以前的经典解决方案,使其安全。

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

任何更好的建议?

推荐答案

每个表的单个身份字段限制的解决办法只是将 Docu将表格转入另一个包含代码字段和任何相关字段的表。

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.

为了获得代码标识字段的基础值(基于日期)可以简单地用最低期望值种子。不知道底层的RDMS,但对于MySQL来说,它将沿着 http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html

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

所以,像

Documents 1-1 DocumentCodes

其中:

DocumentCodes
-------------
code : identity (seeded to desired base value)
documentId : int FK UNIQUE 

另外一个替代方案是允许单独生成代码字段(包括之前的),实际的Document实体将是如下:

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.


  1. 在DocumentCodes表中创建一个实体,并获取生成的代码

  2. 根据生成的代码和从日期生成的号码为最终用户创建计算代码

  3. 创建文档实体,传递生成的代码

根据代码搜索文档:


  1. 从计算的代码中剥离日期部分

  2. 在代码
  3. 中的文档表中搜索
  1. Strip the date part off the computed code
  2. Search in the Document table on code

这篇关于EF6:如何根据实体ID自动生成唯一编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆