Background: I have an object with a dozen or so properties. The object is instantiated by passing a GUID to the constructor. This GUID is a primary key used to retrieve the property values from the database. Each property is stored in a separate table in the database. We are using EF4 to connect to the database.
Is it better to get all the properties at once from the database or is it better to fetch the property values from the database when the property is actually used in the code? What is the recommended best practice?
I would probably change the code to pass a Guid to a static factory method, which then did the lookup, and passed the recovered entity to the constructor. That way the constructor itself doesn’t have to do as much work.
In most cases I would do all this eagerly though – it’s usually odd to have an object which “feels” simple, but which then does potentially expensive and fallible database lookups when you access properties. And yes, you should strive to fetch everything in one database lookup – unless one of the properties is actually a collection in itself, etc. If it’s just a case of fetching simple fields from the database, it would be crazy to perform one lookup per property access – which could end up giving inconsistent data, too.