Null reference exception is thrown when using Database.Select[Distinct]

Null reference exception is thrown when using Database.Select[Distinct]

TRuhlandTRuhland Posts: 5Questions: 1Answers: 0

Hi,

I'm using Databases.dll version 1.5.1.0.

If you try to get a data table via ...

Database database = new Database("sqlserver", Properties.Settings.Default.ConnectionString);
DataTable dataTable = database.Select("myTable").DataTable();

.. and omit the fields parameter which should result to a "SELECT * FROM ..." you will get a null reference exception because the method ...

public Result Select(string table, IEnumerable<string> field = null, Dictionary<string, dynamic> where = null, IEnumerable<string> orderBy = null)
{
    return Query("select")
        .Table(table ?? "*") // BTW: Is this correct ? You can't say SELECT a,b,c FROM * !!!
        .Get(field)
        .Where(where)
        .Order(orderBy)
        .Exec();
}

calls method ...

public Query Get(IEnumerable<string> fields)
{
    foreach (var field in fields)
    {
        Get(field);
    }

    return this;
}

... which does not "know" that fields can be null. So if you change the code to ...

public Query Get(IEnumerable<string> fields)
{
    if (fields == null || fields.Count() == 0)
    {
        Get("*");
    }
    else
    {
        foreach (var field in fields)
        {
            Get(field);
        }
    }

    return this;
}

... everything works fine.

Regards,

Thilo

Replies

  • allanallan Posts: 54,900Questions: 1Answers: 8,605 Site admin

    Hi Thilo,

    Table(table ?? "*") // BTW: Is this correct ? You can't say SELECT a,b,c FROM * !!!

    No - that is complete nonsense! The Select method should in fact look like:

                if (field == null)
                {
                    field = new [] {"*"};
                }
    
                return Query("select")
                    .Table(table)
                    .Get(field)
                    .Where(where)
                    .Order(orderBy)
                    .Exec();
    

    and likewise the SelectDistinct method. That results in the get fields not being empty.

    Thanks for pointing this out!

    Regards,
    Allan

This discussion has been closed.