Question

I have a class as shown below which has a corresponding table in Access 2007

Class Product
{
    public int ProductId
    {
        get;set;
    }
    public string ProductName
    {
        get;set;
    }
    public string ProductColor
    {
        get;set;
    }
}

this is the method i use for adding product to database.

public static void AddProduct(Product product)
    {
        con.Open();
        string strSql = @"INSERT INTO PRODUCTS (PRODUCTID,PRODUCTNAME,PRODUCTCOLOR)
                        VALUES(?,?,?)";
        IDbCommand cmd = con.CreateCommand();
        cmd.CommandText = strSql;

        dh.AddInParam(cmd, "@productId", DbType.Int32, product.ProductId);
        dh.AddInParam(cmd, "@productName", DbType.String, product.ProductName);
        dh.AddInParam(cmd, "@productColor", DbType.String, product.ProductColor);
        cmd.ExecuteNonQuery();
        con.Close()
    }

Now I do not mind if the user entered some null values. In that case how can i update the AddProduct method? The only case coming to my mind is doing a null check for each parameter like below..

if(product.ProductColor = null)
{
    dh.AddInParam(cmd, "@productColor", DbType.String, DbNull.Value);
}
else
{
    dh.AddInParam(cmd, "@ProductColor, DbType.String, product.ProductColor)
}

Am i missing something obvious? What would be the best method for checking nulls in these parameterized queries?

Was it helpful?

Solution

Null coalescing operator could be the solution

dh.AddInParam(cmd, "@productId", DbType.Int32, 
                    product.ProductId ?? (object)DBNull.Value); 

This requires the third parameter of dh.AddInParam to be of object datatype (It should already be this way)

Probably this requirement will be true for every parameter you pass to AddInParam, so the best way to solve this problem is changing the code of this method to account for null values passed in. (Of course, if you have the source)

OTHER TIPS

how about using the NULL coalescing operator?

dh.AddInParam(cmd, "@productColor", DbType.String, product.ProductColor ?? DbNull.Value);

try using null coalescing operator

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top