Entity Framework code first relationships and navigation property?

浪尽此生 提交于 2019-12-12 01:52:53

问题


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

  1. have i done it correctly ?
  2. do i need a navigation property in the Subject class?
  3. 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;} 
        }
    
  4. if i do the above what changes do i need in the configuration and why?

  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 ?

回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!