C # query and SQL Server returning null columns on a large table

I execute the following query in a table containing about 600 columns:

SELECT * 
FROM Table 
WHERE [Owner] = 1234

I run this query using EF code and Dapper and I am facing the same issue with both.

In particular, many rows that DO matter are returned as DBNullfrom a query (I checked using SQL Server Management Studio that the column data has data). Curiously, this only happens when querying all columns (using *or pulling them explicitly).

For example, if a column Statushas a value "A", the query returns DBNullas its value. But if instead of the above code (which pulls out 600 columns), I use this query:

SELECT [Status] 
FROM Table 
WHERE [Owner] = 1234

Status .

Dapper, :

public IList<Dictionary<string, string>> GetData() {
    var sql = "SELECT * FROM Table WHERE [Owner] = 1234";
    var cn = new SqlConnection(serverConnectionString);
    var rows = new List<Dictionary<string, string>>();

    using (var reader = cn.ExecuteReader(sql))
    {
        while (reader.Read())
        {
            var dict = new Dictionary<string, string>();

            for (var i = 0; i < reader.FieldCount; i++)
            {
                var propName = reader.GetName(i).ToLowerInvariant();

                // This is set to DBNull for most, but not all,
                // columns if querying the ~600 columns in the Table
                var propValue = reader.GetValue(i); 

                dict[propName] = propValue?.ToString();
            }

            rows.Add(dict);
        }
    }

    return rows;
}

. .

+4
1

Dapper.Query() . :

[Test]
public void Test_Large_Number_of_Columns()
{
    const int n = 600;
    var cols = "";

    for (var i = 0; i < n; i++)
    {
        cols += "col" + i + " varchar(50) null,";
    }

    var create = String.Format("IF OBJECT_ID('dbo.foo', 'U') IS NOT NULL DROP TABLE dbo.foo; create table foo({0})", cols);

    using (var conn = new SqlConnection(@"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=foo"))
    {
        conn.Execute(create);

        conn.Execute("insert into foo(col300) values('hello') ");

        var result = conn.Query("select * from foo").AsList();

        Assert.That(result[0].col300, Is.EqualTo("hello"));

    }
} 
+1

Source: https://habr.com/ru/post/1682009/


All Articles