问题
i have the following classes
public class Subject{
public int SubjectId { get; set; }
public String SubjectName { get; set; }
public String SubjectCategory { get; set; }
}
public class QuestionDescriptor {
public int QuestionDescriptorId { get; set; }
public String QuestionText { get; set; }
public String Answer { get; set; }
public int SubjectId { get; set; }
public virtual Subject Subject { get; set; }
}
i have configured it using the following code ,i want that a Subject can have many QuestionDescriptors
modelBuilder.Entity<QuestionDescriptor>()
.HasRequired(qd => qd.Subject)
.WithMany()
.HasForeignKey(qd => qd.SubjectId)
.WillCascadeOnDelete(true);
Now i have the following question
- have i done it correctly ?
- do i need a navigation property in the Subject class?
what happems if i do this
public class Subject { public int SubjectId { get; set; } public String SubjectName { get; set; } public String SubjectCategory { get; set; } public int QuestionDescriptorId {get;set;} public virtual QuestionDescriptor {get;set;} }
if i do the above what changes do i need in the configuration and why?
- if i want all the questions belonging to a particular subject then i can get them by querying the QuestionDescriptor ,why then do i need a bi-directional property ?
回答1:
1) have i done it correctly ?
Yes.
2) do i need a navigation property in the Subject class?
No. You don't need it. It can be helpful for certain queries but it is not required.
3) what happems if i do this ...
That's another relationship. It would represent a one-to-one relationship. But because you want a one-to-many relationship you must have a navigation collection on your entity:
public class Subject {
public int SubjectId { get; set; }
public String SubjectName { get; set; }
public String SubjectCategory { get; set; }
public virtual ICollection<QuestionDescriptor> Descriptors {get;set;}
}
4) if i do the above what changes do i need in the configuration and why?
For the change above you can leave you mapping configuration as it is - with the only exception that you now must specify the collection as the other side of the relationship. Instead of .WithMany()
you use
.WithMany(s => s.Descriptors)
5) if i want all the questions belonging to a particular subject then i can get them by querying the QuestionDescriptor ,why then do i need a bi-directional property ?
You don't need it.
来源:https://stackoverflow.com/questions/7619227/entity-framework-code-first-relationships-and-navigation-property