簡體   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