Assume you have a business object with a lot of properties. What is the easiest and best way to set the properties without the use of an ORM tool?
This implies setting properties from a data reader object, such as
client.Name = (string)reader["Name"];
What about the case where the object contains other complex objects?
Any suggestions?
-
Serialization and/or Reflection is an option.
sduplooy : Reflection poses a problem where the column name does not match the objects corresponding property name.Sandy : Unless you specify a mapping between column names and property names, you can't achieve what you want. Specifying such a mapping brings you to building a custom ORM, or using an existing one. -
Well, you could use reflection to generate the assignation code.
-
You ask for three different things:
- quickest
- easiest
- best
they are not the same! The quickest (at execution) would be compiled code; i.e. you write regular C# to set the properties correctly. Easier than this is using reflection - but that is slow. You'd also need some mechanism for mapping child properties... (and also mapping regular properties if there isn't a 1:1 correspondance between the reader). This is perhaps best solved with custom attributes on members (properties/fields).
As a compromise on speed (over reflection), you can use Delegate.CreateDelegate to get at the property setters - but that is a lot of work. Perhaps another option is HyperDescriptor; this allows reflection-like access, but is vastly faster.
Best? Probably to use existing code - i.e. an ORM tool; less to write and debug.
Brann : well, I guess by quickest, he meant quickest to write, not quickest to execute.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.