I'm reading an SqlCeDataReader and assessing values like so:
if(reader["abc"] != DBNull.Value)
Abc = (int)reader["abc"];
if(reader[dude] != DBNull.Value)
Dude = (string)reader[dude];
int Abc
{
get;
set;
}
string Dude
{
get;
set;
}
And I wanted to condense it to one function but with a minimum amount of code, ideally I'd like something like:
Dude = GetField( "dude", reader );
And have it work itself out returning NULL if there's nothing to return. Is that possible?
You could write an extension method like:
public static string GetSafeString(this IDataReader reader, string name)
{
int ordinal = reader.GetOrdinal(name);
return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
}
and use:
Dude = reader.GetSafeString("dude");
However! Personally I would suggest looking at something like dapper-dot-net, which will handle all the materialization code for you, so you just write:
string region = "North";
var users = connection.Query<User>(
"select * from Users where Region = @region", // <=== query
new { region } // <=== parameters
).ToList();