문제

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.

도움이 되었습니까?

해결책 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>
    }

다른 팁

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 == ....)
{
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top