如何在两端正确创建具有导航属性的EF一对零或一关系

本文关键字:EF 属性 关系 导航 创建 | 更新日期: 2023-09-27 18:16:12

在我的模型中我有两个对象:LeadWorkLead 可能有相关的Work,但Work 必须有相关的Lead。我如何使用EF Code First和Fluent API正确表达这一点?到目前为止,我花了一天的大部分时间来做这件事,但我一无所获。问题(也许?)是,我需要在关系的两边都有导航属性。到目前为止,我是这样配置对象的:

public class Lead {
    public int Id { get; set; }
    public int? WorkId { get; set; }
    public virtual Work Work { get; set; }
}
public class Work {
    public int Id { get; set; }
    //public int LeadId { get; set; } <- I think this is necessary?
    public virtual Lead Lead { get; set; }
}
// this seems to make a one-to-one relationship, but it's setting
// the column references as the Id columns on both sides, so it's wrong...
// Also causes this exception:
// A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.
this.HasOptional(t => t.Work).WithRequired(t => t.Lead);

尝试反向工程测试数据库会产生一对多关系,这不是我想要的。如果您能给我一些建议,我将非常感谢。

如何在两端正确创建具有导航属性的EF一对零或一关系

如果lead是一个主体(lead必须首先存在),类可能是这样的:

public class Lead {
    public int Id { get; set; }
    public virtual Work Work { get; set; }
}
public class Work {
    [Key, ForeignKey("Lead")]
    public int Id { get; set; }
    public virtual Lead Lead { get; set; }
}