我理解以下代码在主体和从属实体之间创建“一对一关系”。
但是,我想问一下:
是否可以创建一对一关系而不在依赖实体中包含导航属性?
如果是,我应该如何重新编写以下代码?
public class Student
{
[Key]
public int Id { get; set; }
public string FullName { get; set; }
public StudentReport StudentReport { get; set; }
}
public class StudentReport
{
[Key, ForeignKey("Student")]
public int Id { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
public Student Student { get; set; }
}
答案 0 :(得分:2)
要在依赖方创建一对一关系而不使用导航属性,您需要使用fluent API。例如,在DbContext
类中,您可以覆盖OnModelCreating
并使用它来定义关系:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// I'm assuming the report is optional
modelBuilder.Entity<Student>()
.HasOptional(t => t.StudentReport)
.WithRequired();
}
public class StudentReport
{
public int Id { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
}
请参阅WithRequired()
here