【问题标题】:How do i create One-to-One to relationship without having navigation property in dependent entity如何在依赖实体中没有导航属性的情况下创建一对一关系
【发布时间】:2015-07-28 17:46:59
【问题描述】:

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

不过,我想问一下:

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

【问题讨论】:

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


    【解决方案1】:

    要在依赖端创建没有导航属性的一对一关系,您需要使用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的文档

    【讨论】:

    • 感谢您的回答。外键呢?因此,对于上面的示例,我假设“StudentReport”(依赖)实体中的“Id”将是主键和外键。如果我错了,请纠正我?
    • 第二点:使用您的方法(Fluent API),我还需要在 Principle 实体(学生)中定义导航属性吗?即公共 StudentReport StudentReport { get;放; }
    • @immirza:默认情况下,当EF中存在一对一关系时,依赖实体的主键用作外键。如果您首先使用代码,则关系中的至少一个实体需要具有导航属性(否则,EF 如何知道这些实体是相关的?)
    • @immirza:该语句可能会覆盖HasOptional(..).WithRequired(),因为它定义了与相同实体和相同导航属性的不同关系。如果你愿意,你可以在WithRequired()之后添加.WillCascadeOnDelete(),不过我认为如果你为每个StudentReport设置Student,它应该默认级联删除。
    • @immirza:上面的答案将Student 设置为StudentReport 的要求。如果您有一个StudentReport.Student 导航属性,那么它将是WithRequired(sr =&gt; sr.Student),但由于您不打算在该方向上拥有一个导航属性,因此暗示当您拥有WithRequired() 时,需要Student。你可以把它想象成一句话:“A Student has an optional StudentReport with a required (Student)。”
    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 2022-07-18
    • 2017-10-14
    • 2018-12-27
    相关资源
    最近更新 更多