How to ensure certain properties are always populated when returning object from DAL?
I have a Question
class which has a property OptionList
, which is nothing but a List. Questions and Options are stored in diff tables in the db.
开发者_如何学GoNow there are times when I need just the Question object without its Relational Properties, that is properties which are entities mapping to a different table in the db. Thus in this case I do not need OptionList populated.
But then again there are times when I need the OptionList
Property to be populated.
The approach I am thinking of right now is having two different methods.
public Question GetQuestionByID(int qid)
public Question GetQuestionWitOptions(int qid)
So if I call the second metho, I ensure OptionList is populated in the returned Question object.
Is this a good way to achieve such a result? any alternate ideas and suggestions?
I'd say it's a pretty good method. You're using defined names with an obvious purpose and function.
The only other suggestion I can think of is to create a second class:
public class QuestionExtended : Question
{
public QuestionExtended(IEnumerable<Option> options) : base()
{
OptionList = new List<Option>(options);
}
public List<Option> OptionList { get; private set;}
}
So then the actual class implementation gives an obvious meaning as to what's inside it and what's required for it.
What you have is probably simplest and makes it clear exactly what the method is doing.
The only other alternative is to write an overloaded version:
public Question GetQuestion(int qid, bool withOptions = false)
精彩评论