2013-06-30 45 views
3

我正在做一種使用實體框架代碼優先的測試生成應用程序。我有一個名爲Question的基類,其中MultipleChoiceQuestion,EssayQuestion和其他問題類型下降。 MultipleChoiceQuestions顯然有多個答案,考生必須從中選擇。我的問題與選擇將它們存儲在問題實例中的最佳方式有關。MVC4模型屬性應該是一個列表或另一個類的ICollection

我可以用字符串列表聲明類來保存答案,就像這樣:

public class MulitpleChoiceQuestion : Question 
{ 
    private List<String> Answers = new List<String>(); 
    // other declarations, etc. 
} 

相反,我可以聲明稱爲Answers另一個類,並讓我Question類使用的答案的集合。

public class Answer 
{ 
    public int AnswerID { get; set; } 
    public String AnswerText { get; set; } 

    public virtual Question Question { get; set; } 
} 

然後在我的問題的子類(不只是MultipleChoiceQuestions

public class MulitpleChoiceQuestion : Question 
{ 
    public virtual ICollection<Answer> Answers { get; set; } 
    // other declarations, etc. 
} 

難道還有比任一一個更好的辦法?如果不是,哪個更好,爲什麼?我很難在網絡上找到任何詳細的信息,而且大多數書籍都不會很深入。 在此先感謝您的任何指導。

回答

1

我問我的一個.NET教授朋友這個問題,這就是他的回答:

您的聲明兩者都調用集合。列表是鍵入的 集合,而ICollection是無類型的。與無類型集合相比,鍵入集合(列表)具有 兩個優點。在編譯時檢查每個集合 的類型,從而防止運行時錯誤。第二, 他們減少檢索 對象時所需的鑄造量。

我第一次實現了ICollection的解決方案,它在幾個地方是笨重(例如,種子數據的初始化):

var mcQuestions = new List<MultipleChoiceQuestion> 
    { 
     new MultipleChoiceQuestion { 
      QuestionText = "What is the value returned by the expression (true == false? 'yes': 'no')?", 
      Answers = new List<Answer> { new Answer { AnswerText="true"}, new Answer { AnswerText = "false"}, new Answer { AnswerText = "can't be determined"}, new Answer {AnswerText = "45"}, new Answer { AnswerText = "blue"}} 
     }, 
     new MultipleChoiceQuestion { 
      QuestionText = "C-Sharp responds to a global variable declaration by:", 
      Answers = new List<Answer> { new Answer { AnswerText="throwing a compile error"}, new Answer { AnswerText = "throwing a runtime error"}, new Answer { AnswerText = "Throwing an Invalid operator warning"}, new Answer {AnswerText = "Printing a warning to the console"}, new Answer { AnswerText = "doing nothing; global variables are legal"}} 
     } 
    }; 
    mcQuestions.ForEach(mcq => context.MultipleChoiceQuestions.Add(mcq)); 
    context.SaveChanges(); 

雖然這種解決方案可以更加靈活,我想從長遠來看,清單將更清潔,更易於維護。我想不出一個理由來保持複雜性,作爲未來可能的靈活性的權衡。所以這是我的名單。 希望這可以幫助別人。 祝你好運,而且代碼很好。 J

0

我還沒有嘗試過類似的東西,但我期望EF將您的列表變成您數據庫端的單獨的Answers表,因此我期望這兩種解決方案都會導致相同的數據庫模型。無論如何,如果兩種方法都起作用,決定選擇哪一種方法將是一個有趣的問題。

就我個人而言,我會與列表一起看,因爲它看起來像最簡單的解決方案,簡單通常更好。如果你希望你的班級能夠更好地代表你的數據庫,這可能是一個獨立的答案班的理由。如果您希望將來擴大您的答案,那麼可能是另一個選擇單獨列表中的Answer類的另一個原因。

總的來說,我會說:如果您有兩種解決問題的方法,那麼選擇一種方法是使代碼在查看代碼時最容易閱讀/理解的方法。

+0

感謝您的意見。我同意,在這種情況下更簡單。 – JohnG

相關問題