2013-06-30 44 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

相关问题