如何将数据库表内容发送到API?

时间:2019-06-19 22:32:45

标签: c# sql-server

我在SQL Server数据库表中有记录,需要将其传输到付款处理API。仅将Transmitted = 0的表记录发送到API。我发现this question可以帮助我理解手头的错误。

我想将数据库表中的记录读取到C#类中,解析为JSON,然后通过API调用发送。我尝试使用Entity Framework Core,但是在调用存储过程并将结果添加到模型类中时收到Null Reference异常,如下所示:

        public async Task<IEnumerator<Onboarding>> GetOnboardingList()
    {
        try
        {
            using (var context = new SOBOContext())
            {
                var ob = await context.Onboarding
                    //.Where(o => o.Transmitted == false)
                    .FromSql("Execute GetUnsentOnboardingRecords_sp")
                    .ToListAsync();
                Console.WriteLine(ob.ToArray());
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        return new OnboardingList().GetEnumerator();
    }

当尝试使用Entity Framework Core时,我创建了OnboardingList类,如下所示:

public class OnboardingList : IEnumerable<Onboarding>
{
    private readonly List<Onboarding> _onboarding;

    public IEnumerator<Onboarding> GetEnumerator()
    {

        return _onboarding?.GetEnumerator();
    }        

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _onboarding.GetEnumerator();
    }
}

然后我恢复为SqlDataReader,该方法调用存储过程。该方法的部分内容如下:

var listOnboardingModel = new List<Onboarding>();
        try
        {
            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("GetUnsentOnboardingRecords_sp", connection)
                {
                    CommandType = CommandType.StoredProcedure
                };
                connection.Open();

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        listOnboardingModel.Add(new Onboarding
                        {
                            OnboardingId = reader[1] as int? ?? 0,
                            UserId = reader[2] as int?,
                            UserName = reader[3].ToString(),
                            FirstName = reader[4].ToString(),
                            MiddleInitial = reader[5].ToString(),
                            Lastname = reader[6].ToString(),
                            DateOfBirth = reader[7].ToString(),
                            Ssn = reader[8].ToString(),
                            Email = reader[9].ToString(),
                            Address1Line1 = reader[10].ToString(),
                            Address1Line2 = reader[11].ToString(),
                            Address1ApartmentNumber = reader[12].ToString(),
                            Address1City = reader[13].ToString(),
                            Address1State = reader[14].ToString(),
                            Address1ZipCode = reader[15].ToString(),
                            Address1Country = reader[16].ToString(),
                            DayPhone = reader[17].ToString(),
                            EveningPhone = reader[18].ToString(),
                            PhonePin = reader[19].ToString(),
                            MerchantSourceIp = reader[20].ToString(),
                            ThreatMetrixPolicy = reader[21].ToString(),
                            SessionId = reader[22].ToString(),
                            BankAccount1CountryCode = reader[23].ToString(),
                            BankAccount1Name = reader[24].ToString(),
                            BankAccount1Description = reader[25].ToString(),
                            BankAccount1Number = reader[26].ToString(),
                            BankAccount1OwnershipType = reader[27].ToString(),
                            BankAccount1Type = reader[28].ToString(),
                            BankAccount1BankName = reader[29].ToString(),
                            BankAccount1RoutingNumber = reader[30].ToString(),
                            BankAccount2CountryCode = reader[31].ToString(),
                            BankAccount2Name = reader[32].ToString(),
                            BankAccount2Number = reader[33].ToString(),
                            BankAccount2OwnershipType = reader[34].ToString(),
                            BankAccount2Type = reader[35].ToString(),
                            BankAccount2BankName = reader[36].ToString(),
                            BankAccount2Description = reader[37].ToString(),
                            BankAccount2RoutingNumber = reader[38].ToString(),
                            AuthSginerFirstName = reader[39].ToString(),
                            AuthSignerLastName = reader[40].ToString(),
                            AuthSignerTitle = reader[41].ToString(),
                            AverageTicket = reader[42] as int? ?? 0,
                            BusinessLegalName = reader[43].ToString(),
                            BusinessApartmentNumber = reader[44].ToString(),
                            BusinessAddressLine1 = reader[45].ToString(),
                            BusinessAddressLine2 = reader[46].ToString(),
                            BusinessCity = reader[47].ToString(),
                            BusinessState = reader[48].ToString(),
                            BusinessZipCode = reader[49].ToString(),
                            BusinessCountry = reader[50].ToString(),
                            BusinessDescription = reader[51].ToString(),
                            DoingBusinessAs = reader[52].ToString(),
                            Ein = reader[53].ToString(),
                            HighestTicket = reader[54] as int? ?? 0,
                            MerchantCategoryCode = reader[55].ToString(),
                            MonthlyBankCardVolume = reader[56] as int? ?? 0,
                            OwnerFirstName = reader[57].ToString(),
                            OwnerLastName = reader[58].ToString(),
                            OwnerSsn = reader[59].ToString(),
                            OwnerDob = reader[60].ToString(),
                            OwnerApartmentNumber = reader[61].ToString(),
                            OwnerAddress = reader[62].ToString(),
                            OwnerAddress2 = reader[63].ToString(),
                            OwnerCity = reader[64].ToString(),
                            OwnerRegion = reader[65].ToString(),
                            OwnerZipCode = reader[66].ToString(),
                            OwnerCountry = reader[67].ToString(),
                            OwnerTitle = reader[68].ToString(),
                            OwnerPercentage = reader[69].ToString(),
                            BusinessUrl = reader[70].ToString(),
                            CreditCardNumber = reader[71].ToString(),
                            ExpirationDate = reader[72].ToString(),
                            NameOnCard = reader[73].ToString(),
                            PaymentMethodId = reader[74].ToString(),
                            PaymentBankAccountNumber = reader[75].ToString(),
                            PaymentBankRoutingNumber = reader[76].ToString(),
                            PaymentBankAccountType = reader[77].ToString(),
                            Transmitted = reader[78] as bool?,
                            TransmitDate = reader[79].ToString(),
                            InternationalId = reader[80].ToString(),
                            DriversLicenseVersion = reader[81].ToString(),
                            DocumentType = reader[82].ToString(),
                            DocumentExpDate = reader[83].ToString(),
                            DocumentIssuingState = reader[84].ToString(),
                            MedicareReferenceNumber = reader[85].ToString(),
                            MedicareCardColor = reader[86].ToString(),
                            PaymentBankAccountName = reader[87].ToString(),
                            PaymentBankAccountDescription = reader[88].ToString(),
                            PaymentBankCountryCode = reader[89].ToString(),
                            PaymentBankName = reader[90].ToString(),
                            PaymentBankOwnershipType = reader[91].ToString()
                        });
                    }

                }

                connection.Close();

            }
            Console.WriteLine(listOnboardingModel);

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return listOnboardingModel;

运行控制台应用程序时,收到错误Exception thrown: 'System.IndexOutOfRangeException' in System.Data.SqlClient.dll Index was outside the bounds of the array.

如何防止上述超出范围的异常,并确保包括数据库表中的所有合格记录以进行传输?

1 个答案:

答案 0 :(得分:3)

您似乎有两个不同的问题:

  1. .ToString()为空值,这将导致空引用异常。
  2. 序数可能超出范围,一列与所提供的数值不匹配,导致其超出范围。

检查DBNull.Value,否则将出现第一点。 我的假设是,您从1开始,而索引从零开始。因此,第一列将从零开始而不是一个。

您应该为D SqlDataReader查找Dapper或某些内置实用程序,以利用更简洁的代码调用来构建对象。 Dapper只需执行以下操作即可压缩代码:

IEnumerable<Sample> GetSamples() => dbConnection.Query<Sample>(...);

只要列名与属性名匹配,它就会填充。根据提供的实体,它看起来非常简单,但请查阅文档。

另外,您应该像这样将命令包装在using语句中,这样就不会有人意外地在连接块中间调用command.Dispose()

using(var connection = new SqlConnection(...))
using(var command = new SqlCommand(..., ...))
{
     connection.Open();
     ...
     using(var reader = command.ExecuteReader())
         while(reader.Read())
         {

         }
}