簡體   English   中英

實體框架核心:使用復合鍵映射1到1關系

[英]Entity-Framework-Core: Mapping 1 to 1 Relationships using Composite Keys

我很難使用FluentAPI在EntityFrameworkCore中配置1:1映射。 導航參考始終為NULL。 我的代碼與我檢查過的其他代碼之間唯一的明顯區別是,我試圖通過組合鍵進行映射。

我使用注解代替Fluent API玩耍,但是遇到了我的摘要中描述的相同問題。

類定義

[Table("SomeTable")]
public class Defect
{
    [Column("Record")]
    public int DefectId { get; set; }
    [Column("insp_id")]
    public int InspId { get; set; }
    [Column("defectnum")]
    public int Number { get; set; }

    public virtual Simulation Simulation { get; set; }
}


[Table("SomeSimulationTable")]
public class Simulation
{
    [Column("Record"), Key]
    public int SimTableId { get; set; }
    [Column("insp_id")]
    public int InspId { get; set; }
    [Column("DefectNumber")]
    public int Number { get; set; }

    [Column("SimulationName")]
    public string Name{ get; set; }
    [Column("SimulationAlgorithm")]
    public string Algorithm{ get; set; }

    public virtual Defect Defect { get; set; }
}

Fluent API(在OnModelCreating中)

 modelBuilder.Entity<Defect>()
     .HasKey(h => new { h.InspId , h.Number });

 modelBuilder.Entity<Defect>()
     .HasOne<Simulation>(p => p.Simulation)
     .WithOne(i => i.Defect)
     .HasForeignKey<Simulation>(b => new { b.InspId , b.Number });   

通過dbContext填充“ Defect”類時,所有數據均可用。 但是,當我嘗試訪問“缺陷”類的“模擬”屬性時,遇到以下錯誤:

System.NullReferenceException:'對象引用未設置為對象的實例。

我還驗證了我們的數據庫中“缺陷”應具有“模擬”的有效數據。

有什么幫助嗎? 把自己扔在其他編碼者的擺布下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM