mercredi 22 juin 2016

SqlDataReader not returning all rows when adding to List<MyClass>

I am attempting to grab some organization data from a db. I need some more data, but I am stuck at just the org name, and org address. I am attempting to perform a query that involves a join, and create an object, which is a list of a custom class I have created. The weird thing is, if I comment the code in my while loop, and just get the name of the orgs, it works, but as soon as I try to create a list of objects, it doesn't.

Here is what I've got, starting with my class:

namespace FFDFrameWorkPart
{
    public class OrgData
    {
        public string orgName { get; set; }
        public string orgAddress { get; set; }
    }
}

List<OrgData> OrgObject = new List<OrgData>();
List<string> orgName = new List<string>();
    using (SqlConnection connection = new SqlConnection(connectString))
    {
        connection.Open();
        SqlCommand GrabOrgsFromDb = new SqlCommand(getConstitData, connection);
        SqlDataReader reader = GrabOrgsFromDb.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                orgName.Add(reader.GetString(0));
                OrgObject.Add(new OrgData()
                {
                    orgName = reader.GetString(0),
                    orgAddress = reader.GetString(1)
                 });
            }
        }
        catch (Exception ex)
        {
            consoleLog.Value = ex.ToString();
        }
        finally
        {
            reader.Close();
        }
    }

Running that code results in orgName.Count and OrgObject.Count to be in the neighborhood of 20.

If I just comment out

OrgObject.Add(new OrgData()
{
    orgName = reader.GetString(0),
    orgAddress = reader.GetString(1)
});

Then orgName.Count jumps to about 28,000. No other change to the code is necessary, just comment out where I am trying to build my list, and I lose around 28,000 records from my results.

EDIT: It's hitting a null value in one of the fields and stopping

Aucun commentaire:

Enregistrer un commentaire