Reputation: 5977
I am starting a new ASP.Net MVC 5 project and using EF5 and Code First with it. Since I am new to EF, i am trying to figure out how to setup the relationship between two classes so it works the way I want.
I am modeling a "test." There is a Test class and a Questions class. The user builds a Test by adding one or more questions and setting the question order. So we not only have a one-to-many relationship between test and question, but a manual ordering of those questions for the given test (the questions come from a generic pool and the teachers can build their individual tests from that pool but order the questions how they want),
I understand how to get the normal, basic one-to-many relationship in EF. But how to handle the ordering within that relationship? Do I just create my own "linking" class instead of letting EF build the linking table for me? Can I tweak something in Data Annotations or Fluent API to make this work (I have been using DA and not Fluent, but would be willing to use it if it helps).
Upvotes: 2
Views: 411
Reputation: 236228
If different users can use same questions in different order, then you should create linking table (entity) between test and questions, which will hold order of question. Something like this:
public class Test
{
// ...
public virtual ICollection<TestQuestion> Questions { get; set; }
}
public class TestQuestion
{
public virtual Test Test { get; set; }
public virtual Question Question { get; set; }
public int Order { get; set; }
}
public class Question
{
// ...
}
And mapping will look like:
modelBuilder.Entity<Test>()
.HasMany(t => t.Questions)
.WithRequired(tq => tq.Test);
modelBuilder.Entity<TestQuestion>()
.HasRequired(tq => tq.Question)
.WithOptional();
Upvotes: 1