Question

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.

Was it helpful?

Solution 2

This was more simple than I expected. I just needed to use a foreach loop:

    @foreach (var question in item.Questions)
    {
        <td>@question.question1</td>
    }

OTHER TIPS

ICollection<T> is just like an IList<T> or T[], so you're going to have to get an element within the collection first then reference its properties. e.g.

Test test = testService.Get(1);
Question question = test.Questions.FirstOrDefault(); // using System.Linq;
if (question.quertionType == ....)
{
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top