Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何按不同的应用程序类型生成序列唯一编号_C#_Asp.net Mvc_Entity Framework - Fatal编程技术网

C# 如何按不同的应用程序类型生成序列唯一编号

C# 如何按不同的应用程序类型生成序列唯一编号,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我已经构建了一个MVC web应用程序,需要在用户提交表单时按应用程序类型和年份生成一个唯一的序列号 序列号将存储在数据库表MyAppCodeSEQ中,“AppCode”列是MyAppCodeSEQ的主键 下面是我的代码: public MyAppCodeSEQ GenNewAppCode(string appType) { MyAppCodeSEQ model = null; try { var today = DateTime.Now;

我已经构建了一个MVC web应用程序,需要在用户提交表单时按应用程序类型和年份生成一个唯一的序列号

序列号将存储在数据库表MyAppCodeSEQ中,“AppCode”列是MyAppCodeSEQ的主键

下面是我的代码:

public MyAppCodeSEQ GenNewAppCode(string appType)
{
    MyAppCodeSEQ model = null;
    try
    {
        var today = DateTime.Now;

        int maxSeq = _db.MyAppCodeSEQ.Where(x => x.AppType == appType && x.Year == today.Year).Select(x => x.SEQ).DefaultIfEmpty(0).Max();

        maxSeq = maxSeq + 1;
        var appCode = "XX" + appType + today.Year % 1000 + string.Format("{0:000000}", maxSeq);

        model = new MyAppCodeSEQ()
        {
            AppCode = appCode,
            AppType = appType,
            Year = today.Year,
            SEQ = maxSeq,                        
        };

        _db.MyAppCodeSEQ.Add(model);
        _db.SaveChanges();             
    }
    catch(Exception e)
    {      
        Thread.Sleep(100);
        GenNewAppCode(appType);
    }

    return model;
}
插入重复钥匙时,将调用该功能。但是,下面的错误一再出现

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. 
---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. 
---> System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_AppCodeSEQ'. 
Cannot insert duplicate key in object 'dbo.MyAppCodeSEQ'. The duplicate key value is (XXYY18002193).
The statement has been terminated.
 System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
 System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
 System.Data.SqlClient.SqlDataReader.get_MetaData()
 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
 System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
 System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
 System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
 System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
 System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
 System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
 System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
 System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
 System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
 System.Data.Entity.Internal.InternalContext.SaveChanges()
有没有更好的方法来生成序列号

a)永远不要有可编辑的主键,让数据库生成主键

b) 您所说的字段是一个“候选”键,其目的通常是将其“排序”为默认序列或保证唯一性

c) 顺序键几乎是一段毫无意义的数据

也就是说,有一种可能性:


更改您的类(MyAppCodeSEQ)以包含一个添加的字段作为DateTime。AppCode、AppType、Year上的唯一索引,以防止重复。添加了AppCode、AppType、Year上的索引以保留序列。

让数据库通过将主键用作序列号的一部分来为您执行此操作。可能的重复项可能会将序列号的所有组件存储在它们自己的列中,这样,自动递增的
int
部分可以成为主键?您可以有一个
[NotMapped]
列,该列组合参考号供您在代码中使用。通常不需要生成您自己的ID。只需让数据库使用自动增量字段为您创建它。然后,它消除了与生成副本等相关的所有问题。