c# - Extension method to handle database values -
i find myself reading data various sql objects (datatable, sqlreader)) , assigning own custom objects. times cannot sure if data retrieving database null or contains valid data. though make object properties nullable still can't assign object value integer property.
public int? clientid{ get; set; } this.clientid = clienttable.rows[0]["id"];
in above case cannot cast clienttable.rows[0]["id"]
int
because value may null
.
this.clientid = (int)clienttable.rows[0]["id"]; // warning! value null
so thought extension method idea (i got idea this answer) ....
public static int getintfromdb(this datarow row, string columnname) { return row[columnname] int? ?? default(int); }
the extension method called using ...
this.clientid = clienttable.rows[0].getintfromdb("id");
the problem extension method returns integer. there way return null value object property?
sure, make method return int?
instead of int
. heck, can simpler:
public static int? getintfromdb(this datarow row, string columnname) { return row[columnname] int?; }
i'd differently though, avoid masking places you're asking int
different field type:
public static int? getint32fromdb(this datarow row, string columnname) { return row.isnull(columnname) ? (int?) null : (int) row[columnname]; }
Comments
Post a Comment