Note that there are some explanatory texts on larger screens.

plurals
  1. POQuestions with different types of answer in NHibernate
    primarykey
    data
    text
    <p>I'm trying to find a tidy solution to a questionnaire problem. Let us say that I have a <code>Questionnaire</code> class which has a collection of <code>Answer</code>s, e.g.</p> <pre><code>public class Questionnaire { public virtual ISet&lt;Answer&gt; Answers {get;set;} } </code></pre> <p>Answers need to be of different types depending on the question, e.g. date of birth, marks out of ten, why do you think etc.</p> <p>My first thought was something like this:</p> <pre><code>public class Question { public virtual QuestionType TypeOfQuestion {get;set;} public virtual string PromptText {get;set;} } public class Answer { public virtual Question Question {get;set;} } public class DateTimeAnswer : Answer { public virtual DateTime Response {get;set;} } public class IntegerAnswer : Answer { public virtual int Response {get;set;} } // etc. </code></pre> <p>The obvious problem would be that from the questionnaire, there is no access to the <code>Response</code> property:</p> <pre><code>questionnaire.Answers[0].Response; // compile error </code></pre> <p>The same would apply to an interface. It would be nicer to use a generic interface, such as:</p> <pre><code>public interface IAnswer&lt;T&gt; { public virtual Question Question {get;set;} public virtual T Response {get;set;} } public class DateTimeAnswer : IAnswer&lt;DateTime&gt; {} </code></pre> <p>The problem then comes in the <code>Questionnaire</code> class, as the type of IAnswer must be supplied:</p> <pre><code>public class Questionnaire { public virtual ISet&lt;IAnswer&lt;???&gt;&gt; Answers {get;set;} } </code></pre> <p>Clearly I don't want to have many collections of IAnswer each with different types. I could use </p> <pre><code>ISet&lt;IAnswer&lt;dynamic&gt;&gt; </code></pre> <p>but then NHibernate wouldn't like it.</p> <p>I realise a compromise is needed somewhere, but I'm not sure which is the prettiest. What would you do?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload