Question

I am looking for some suggestion over best practice (considering Memory and CPU time) to handle Nullable<T> fields returned from a stored procedure on using Linq2Sql.

Please consider the following scenario and limitations:

  1. I want to avoid using fieldValue.HasValue check everywhere in the code. Thus, I need to replace all Nullable<T> with normal properties (esp DateTime, Double, Int) with some default value.
  2. I am expecting to read ~1million objects with ~20 fields of Nullable type.
  3. Memory and CPU usage is an important consideration.
  4. The requirement is to get result from stored proc in an object (not DataRow), and thus using Linq2Sql.

Please share your opinion or experience over handling a similar situation.

Thanks for your interest.

Was it helpful?

Solution

Best Solution:

  • Don't allow SQL to return NULL Values.

  • The easiest way to do this is to not allow the columns themselves to be null, but if that isn't a possibility then you can do an ISNULL(field, defaultvalue) in the query that you are using to return the data.

Next Best Solution:

  • Overwrite the LINQToSQL objects get call to check if the object HasValue and then if not set it to the default(type) value for the field.

There is no way to not check every value.

OTHER TIPS

You can write extension methods such as:

public static string SafeGetString(this SqlDataReader _Reader, int _ColIndex)
{
    if (_Reader.IsDBNull(_ColIndex))
        return null; //Default value
    else
        return _Reader.GetString(_ColIndex);
}

For each type used (there are actually not so many), set the default value to something other than null if you want to insert the data into non-nullable types.

A hardcore option is to coalesce the values at their source. You'll guarantee that nulls will stay away from the data readers.

But as performance seems to be a big concern, I'd suggest that you measure different options to make an informed decision before compromising the sanity of your code (over-optimizing) or the sanity of your runtime (abusing memory or cpu).

As a side note, fetching millions of rows from a database most certainly will cause sensible impact somewhere. You'll usually have to decide where/when it will hurt less!

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