0

I have some classes that model my tables. Many of the tables have a sql server DateTime, which is a c# DateTime in my classes. The code looks something like "FIGURE 1" below. As I do this often I want to put in a static method that I can call my each of my classes. My problem is that I dont know how to represent the parameter (a specific sqldatreader column/row) in the static method, "FIGURE 2" below.

FIGURE 2

public static DateTime SqlDateTimeSet(????)
{
    DateTime dt;
    if (?????) // // true = null in test
        dt = DateTime.MinValue;
    else
        dt = ????;
    return dt;  
}

FIGURE 1

User usr = new User();
int ordinal = <nullable DateTime column>;
if (dr.IsDBNull(ordinal))
    usr.DisableDate = DateTime.MinValue;
else
    usr.DisableDate = dr.GetDateTime(ordinal);

2 Answers 2

1

You should be able to convert a SQL Date/Time to a .NET DateTime like this (where the passed in value is something from a DataReader like myDataReader["myDateTime"]:

public static DateTime SqlDateTimeSet(object drValue)
{
    DateTime? dt;
    dt = drValue as DateTime?;
    return dt.GetValueOrDefault();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here is an example of a general extension method that will work.

  public static class DataRowExtensions
  {
    public static T FieldOrDefault<T>(this DataRow row, string columnName)
    {
      return row.IsNull(columnName) ? default(T) : row.Field<T>(columnName);
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.