实体框架代码优先关系和导航属性? [英] Entity Framework code first relationships and navigation property?
问题描述
我有以下课程
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; }
}
我已使用以下代码对其进行了配置,我希望一个Subject可以具有许多QuestionDescriptor
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);
现在我有以下问题
- 我做对了吗?
- 我在Subject类中需要导航属性吗?
-
如果我这样做会发生什么
- 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?
推荐答案
1)我做对了吗?
1) have i done it correctly ?
是的
2)我在Subject类中需要导航属性吗?
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)如果我这样做会发生什么...
3) what happems if i do this ...
那是另一种关系.这将代表一对一的关系.但是,由于您想要一对多关系,因此您的实体上必须具有导航 collection :
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)如果执行上述操作,我需要在配置中进行哪些更改, 为什么?
4) if i do the above what changes do i need in the configuration and why?
对于上述更改,您可以保持映射配置不变-唯一的例外是,您现在必须将集合指定为关系的另一侧.代替.WithMany()
而是使用
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)如果我想要属于某个特定主题的所有问题,那么 我可以通过查询QuestionDescriptor来获取它们,为什么我需要 双向属性?
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 ?
您不需要它.
这篇关于实体框架代码优先关系和导航属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!