开发者

Passing sql row/column to method

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" b开发者_如何学Celow.

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);


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();
}


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);
    }
  }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜