문제

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top