문제

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?

도움이 되었습니까?

해결책

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)

다른 팁

how about using the NULL coalescing operator?

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

try using null coalescing operator

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top