使用dapper中的存储过程在c#中自动生成发票编号

时间:2019-06-06 09:52:18

标签: c# sql-server-2016

我想生成自定义事务编号,例如(INV2019-12-000001)并通过使用存储过程保存数据来生成下一个发票编号。

1 个答案:

答案 0 :(得分:0)

您可以使用类似于以下内容的SQL代码在数据库上创建序列对象:

SELECT NEXT VALUE FOR Test.CountBy1TestSequence;  

然后可以使用SQL通过以下方式调用它:

using (var conn = new SqlConnection(ConnectionString))
            {
                String sql = @"SELECT NEXT VALUE FOR Test.CountBy1TestSequence";

                var result = conn.ExecuteScalar<Int>(sql);

                // Do whatever with the result    
            }

或通过dapper调用:

 var p = new DynamicParameters();
 p.Add("@inputInvoiceNumber", $"INV{DateTime.Now.Year}-{DateTime.Now.Month}-{result}, DbType.String, ParameterDirection.Input);
 p.Add("@retVal", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue); // If there is any return

 cnn.Execute("spTestProc", p, commandType: CommandType.StoredProcedure);

使用序列值,然后可以使用dapper将序列值传递给数据库中的存储过程,该代码类似于以下代码:

@inputInvoiceNumber

@retValtype AccountCreation = { Owner: string AccountId: Guid CreatedAt: DateTimeOffset StartingBalance: decimal } type AccountEvents = | AccountCreated of AccountCreation | AccountCredited of Transaction | AccountDebited of Transaction let settings = { Host = "localhost" DatabaseName = "postgres" UserName = "root" Password = "root" EventTypes = eventTypes } use store = createDocumentStore settings use session = store.LightweightSession() let khalidId = Guid.NewGuid() let billId = Guid.NewGuid() let khalid = AccountEvents.AccountCreated({ Owner = "Khalid Abuhakmeh" AccountId = khalidId StartingBalance = 1000m CreatedAt = DateTimeOffset.UtcNow }) let bill = { Owner = "Bill Boga" AccountId = billId StartingBalance = 0m CreatedAt = DateTimeOffset.UtcNow } session.Events.Append(khalidId, khalid) |> ignore session.Events.Append(billId, bill) |> ignore session.SaveChanges() let stream = session.Events.FetchStream() 是存储过程中的参数。