开发者

Are nullable types perfect for my situation?

开发者 https://www.devze.com 2022-12-09 09:42 出处:网络
Recently converted my ASP.NET project from 1.1 to 3.5. Hooray! Currently developing a form which has a handful of optional fields. Normally, I\'d go through in my code, adding tons of if statements, c

Recently converted my ASP.NET project from 1.1 to 3.5. Hooray! Currently developing a form which has a handful of optional fields. Normally, I'd go through in my code, adding tons of if statements, checking for empty field, and setting value to 0 if so. So, I'm wondering if it would be best to instead, declare private, nullable variables for each of these fields, then add these as parameters for my database update? Using MSSQLS 2000, already set the corresponding fields to allow nulls.

To clarify: The web form has fields for dollar amounts. The default value on the inputs is 0, but if the user deletes one of those 0's, leaving the field empty then submits the form, an exception will be thrown at Convert.ToDecimal(MoneyField.Text) in the argument list of the method that submits all this to the database. Is there a cleaner wa开发者_如何学Cy to do this that I'm missing?


It seems unusual that you would have that many fields that are truly nullable, but if you need to describe "no value" separately to any magic domain value of (for example) an int, then yes: Nullable<T> may help. Note that you must manually translate from null to DbNull.Value at the data-layer, as null on a SqlParameter means "don't send this parameter", not "send the value null" (if you see the distinction).


I think there is mix up between field validation and Nullable Type here...unless of course you have a some type ...say DateTime and want that to be null...which would not be possible unless usage of Nullable Type.

If that is the case then ...yes..Nullable types are the solution.


Yup, sounds like a plan.

You'd have to change a couple of calls though

static class NConv
{
    static T? ToNullable<T>(string str) where T : struct
    {
        return (T?)(string.IsNullOrEmpty(str) ? default(T?) : Convert.ChangeType(str, typeof(T)));
    }

    static void HowTo()
    {
        double? myBonus = NConv.ToNullable<double>(null);
    }
}


Dynamically build your sql based upon the fields supplied.

0

精彩评论

暂无评论...
验证码 换一张
取 消