如何在依赖实体中没有导航属性的情况下创建一对一关系

时间:2015-07-28 17:46:59

标签: entity-framework ef-code-first code-first

我理解以下代码在主体和从属实体之间创建“一对一关系”。

但是,我想问一下:

  1. 是否可以创建一对一关系而不在依赖实体中包含导航属性?

  2. 如果是,我应该如何重新编写以下代码?

    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; }
    }
    

1 个答案:

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

的文档