实体框架代码优先关系和导航属性?
我有以下类,
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; }
}
我使用以下代码配置了它,我希望一个主题可以有许多 QuestionDescriptor
modelBuilder.Entity<QuestionDescriptor>()
.HasRequired(qd => qd.Subject)
.WithMany()
.HasForeignKey(qd => qd.SubjectId)
.WillCascadeOnDelete(true);
现在我有以下问题
- 我是否正确完成了?
- 我需要在主题类中添加导航属性吗?
如果我这样做会发生什么
公共类主题 { 公共 int 主题 ID { 获取;放; } 公共字符串主题名称{获取;放; } 公共字符串主题类别{获取;放; } 公共 int QuestionDescriptorId {获取;设置;} 公共虚拟 QuestionDescriptor {get;set;} }
如果我执行上述操作,我需要在配置中进行哪些更改,为什么?
- 如果我想要属于特定主题的所有问题,那么我可以通过查询 QuestionDescriptor 来获取它们,为什么我需要双向属性?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。
不,你不需要它。它对于某些查询可能有帮助,但不是必需的。
那是另一种关系。它代表一对一的关系。但是因为您想要一对多关系,所以您的实体上必须有一个导航集合:
对于上述更改,您可以保留映射配置不变 - 唯一的例外是您现在必须将集合指定为关系的另一方。您使用的不是
.WithMany()
你不需要它。
Yes.
No. You don't need it. It can be helpful for certain queries but it is not required.
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:
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 useYou don't need it.