将 sql 中的日期时间字段读入数据表时出现以下问题。
查询工作正常,但是当我进入 foreach 循环时,它抱怨 datetime 字段中有一个空值。
我有一个类定义为:
public class trading_book_product_IRS
{
public DataTable dt_IRS { get; set; }
public string account_deal_position_id { get; set; }
public DateTime schedule_start_date { get; set; }
public DateTime schedule_end_date { get; set; }
public string repricing_type { get; set; }
public string coupon_type { get; set; }
public string reference_curve { get; set; }
public string reference_curve_point { get; set; }
public decimal interest_rate { get; set; }
public decimal interest_rate_spread { get; set; }
}
我使用以下方法创建了我的数据表,因为我是这样做的,所以我不能使用DateTime
?
public static DataTable CreateDataTable(Type animaltype)
{
DataTable return_Datatable = new DataTable();
foreach (PropertyInfo info in animaltype.GetProperties())
{
if (!info.Name.StartsWith("dt_"))
{
return_Datatable.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
}
return return_Datatable;
}
然后我进行查询并期望写入结果,但是我无法处理 DateTime 为空。我正在尝试做的是:如果日期时间为空,则将日期设为 99990101。问题在于 schedule_end_date 和 schedule_start_date 字段。
var query =
from result in t_sdi_trading_book_product_interest_repricing_schedule_hsbc.AsEnumerable()
where result.sdi_control_id == sdi_id
&& accountDealIDs.Contains(result.account_deal_position_id)
select new trading_book_product_IRS()
{
account_deal_position_id = result.account_deal_position_id,
coupon_type = result.coupon_type,
interest_rate = result.interest_rate,
interest_rate_spread = result.interest_rate_spread,
reference_curve = result.reference_curve,
reference_curve_point = result.reference_curve_point,
repricing_type = result.repricing_type,
schedule_end_date = !string.IsNullOrEmpty(result.schedule_end_date.ToString()) ? result.schedule_end_date : DateTime.Parse("99990101"),
schedule_start_date = !string.IsNullOrEmpty(result.schedule_start_date.ToString()) ? result.schedule_start_date : DateTime.Parse("99990101"),
};
foreach (var results in query)
{
foreach (PropertyInfo result in results.GetType().GetProperties())
{
string name = result.Name;
foreach (PropertyInfo info in used.GetType().GetProperties())
{
if ((result.Name == info.Name) && (!result.Name.StartsWith("dt_")))
{
try
{
info.SetValue(used, result.GetValue(results, null), null);
}
catch (NoNullAllowedException e)
{
}
}
}
}
dt_IRS.Rows.Add(makeRow(used, dt_IRS));
}