Currently I do something like this:
class Foo {
// Declare Fields
[FieldName("F_BAR")] public int? Bar;
[FieldName("F_BAZ")] public int? Baz;
[FieldName("BLARG")] public double? Bee;
// And a custom selector
public static string FooFields() {
// which looks something like:
StringBuilder fields = new StringBuilder();
foreach( FieldInfo f in typeof(Foo).GetFields() )
fields.Append(", " +
f.GetCustomAttributes(
typeof(FieldNameAttribute),
false)[0].FieldName );
return fields.ToString().Substring(2);
}
// .. which will be used like this:
public static string ExampleSelect() {
return "select " + Foo.FooFields() + " from tablename";
}
// And a custom reader, formatted for the custom selector
public static Foo Read(DbDataReader reader) {
int i = -1;
return new Foo {
Bar = reader.IsDBNull(++i)
? (int?)null
: Convert.ToInt32(reader.GetValue(i)),
Baz = reader.IsDBNull(++i)
? (int?)null
: Convert.ToInt32(reader.GetValue(i)),
Bee = reader.IsDBNull(++i)
? (double?)null
: Convert.ToDouble(reader.GetValue(i))
};
}
}
Currently, it works. I realized today, that this depends on the fields being returned from GetFields()
in the order that I declared them in the class. Is this always the expected behavior? Only in .NET?
EDIT: If there are cases when it doesn't work, can I assume it will work as long as I don't do anything to upset the cache?