繁体   English   中英

如何使用两端的导航属性正确创建EF一对零或一个关系?

[英]How to properly create an EF One-to-Zero-or-One relationship with navigation properties on both ends?

在我的模型中,我有两个对象: LeadWork Lead 可能有相关的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);

尝试对测试数据库进行反向工程会产生一对多关系,这不是我想要的。 我将对有关如何正确配置关系的建议表示赞赏。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM