Domanda

My Linq-to-SQL program is returning quite a few values from my SQL Server database some of which the values can be null and others not.

If the DataTable column is cast as string, this is not an issue. However when it is cast as decimal, I get error messages stating decimal cannot be null.

What I need to find out is how I can handle these effectively whilst keeping my code neat.

// Create DataTable
DataTable dt = new DataTable();
dt.Columns.add("Deal", typeof(string));
dt.Columns.add("Price", typeof(decimal) ?? typeof(DBNull));

// Create Linq Query
var query =
    from quer in table 
    select new  
    {
        quer.deal_id,
        quer.price 
    };

Here I create my datarows before inserting into the table:

var datarows = query.Select(r =>
{
    var row = dt.NewRow();
    row["Deal"] = r.deal_id;
    row["Price"] = r.price;
};

Now to ensure that my datarow can handle Nulls, I can just make it nullable but it's not necessary.

dt.Columns.add("Deal", typeof(string?));

But for the decimal field I have to do this:

if (r.price == DBNull.Value)
{
    row["Price"] = null;
}

Now I have to do about 50 of these if statement checks per table I'm designing. Can I just pass it to a function to do?

È stato utile?

Soluzione

You could set your DataColumn to accept DBNull values:

// Create DataTable
DataTable dt = new DataTable();

dt.Columns.add(new DataColumn( "Deal", typeof(string));
dt.Columns.add(new DataColumn( "Price", typeof(decimal)){AllowDBNull = true});

// Create Linq Query
var query =
    from quer in table 
    select new  
    {
        quer.deal_id,
        quer.price 
    };
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top