我发现自己从各种SQL对象(DataTable,SqlReader)中读取数据并分配给我自己的自定义对象.通常,我无法确定从数据库检索的数据是否为空或包含有效数据.虽然我使我的对象属性可以为空但我仍然无法将对象值分配给整数属性.
public int? ClientId{ get; set; } this.ClientId = clientTable.Rows[0]["ID"];
在上面的例子中,我不能将clientTable.Rows[0]["ID"]
as转换为as,int
因为值可能是null
.
this.ClientId = (int)clientTable.Rows[0]["ID"]; // WARNING! value could be null
所以我认为扩展方法是个好主意(我从这个SO答案得到了这个想法)....
public static int GetIntFromDB(this DataRow row, string columnName) { return row[columnName] as int? ?? default(int); }
使用...调用扩展方法
this.ClientId = clientTable.Rows[0].GetIntFromDB("ID");
问题是Extension方法总是返回一个整数.有没有办法将NULL值返回给对象属性?
当然,只是让你的方法返回int?
而不是int
.哎呀,然后它可以更简单:
public static int? GetIntFromDB(this DataRow row, string columnName) { return row[columnName] as int?; }
我个人会稍微改变一下,以避免掩盖你要求int
不同字段类型的地方:
public static int? GetInt32FromDB(this DataRow row, string columnName) { return row.IsNull(columnName) ? (int?) null : (int) row[columnName]; }