views:

59

answers:

3

Currently, whenever I pass a string to the db, if that string is empty, then i set that object to NULL by doing the following:

IIf(DescriptionTxt.Text.length > 0, DescriptionTxt.Text, DBNull.Value)

I was thinking about writing a function to reduce the length of this code, and make it more consistent.

However, I was wondering, is there already a way of doing this in .NET 3.5?

A: 

Your database will perform better and be easier to query properly if you don't put a bunch of nulls in there. I'd stick with "", 0, -1, negative infinity, or some other value appropriate to your situation and change your application code to suit. Avoid unnecessary nulls in your database.

no
I have some optional fields for my news articles, such as Description. Surely its best to store an empty value as NULL, rather than an empty string? Less space, and easier to manage (as in I'll be able to make use of system functions such as ISNULL).
Curt
+1  A: 

You could write an extension method:

public static object AsNull(this string me)
{
    if (string.IsNullOrEmpty(me))
        return DBNull.Value;
    return me;
}

Then in code just use

DescriptionTxt.Text.AsNull()

But otherwise there is nothing in .NET that does it by default. In fact, most developers that I know prefer to make a distinction between a NULL and an empty string. They are different in .NET, so it's a lot easier (and consistent) if they are different in the DB as well.

Added: OOps just noticed this is a VB.NET question. Sorry, my VB.NET is a bit rusty, but I'm sure you will be able to translate the simple function above to VB.NET.

Vilx-
Thanks @Vilx-. In the end I went with: Public Shared Function NullIfEmpty(ByVal Value As String) As String Return IIf(String.IsNullOrEmpty(Value) = False, Value, DBNull.Value) End Function
Curt
@Curt - as they say - same difference! :)
Vilx-
+1  A: 

You pretty much have the simplest code already. There aren't any 3.5 tools to make this simpler. A refinement might be a merge between your code and @Vilx- code:

IIf(String.IsNullOrEmpty(DescriptionTxt.Text), DBNull.Value, DescriptionTxt.Text) 
Joel Etherton