0

I created a MSSQL database with tables containing foreign keys. I then created a new MVC 4 web application. I used Entity Framework to generate my controllers/models/views. In the models, tables that were linked using foreign keys appear as ICollections. For example:

 public partial class Test
{

    public Test()
    {
        this.Questions = new HashSet<Question>();
        this.Users = new HashSet<User>();
    }

    public int testId { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public Nullable<int> pointValue { get; set; }
    public Nullable<int> numberOfQuestions { get; set; }

    public virtual ICollection<Question> Questions { get; set; }
    public virtual ICollection<User> Users { get; set; }

    }
}

My question is how am I able to access the data stored in those ICollections in a view? Test.Questions[x] <-- gives errors.

4

2 回答 2

0

这比我预期的要简单。我只需要使用一个 foreach 循环:

    @foreach (var question in item.Questions)
    {
        <td>@question.question1</td>
    }
于 2013-03-02T06:57:32.190 回答
0

ICollection<T>就像IList<T>or一样T[],因此您必须先在集合中获取一个元素,然后再引用它的属性。例如

Test test = testService.Get(1);
Question question = test.Questions.FirstOrDefault(); // using System.Linq;
if (question.quertionType == ....)
{
}
于 2013-02-25T02:21:07.097 回答