簡體   English   中英

只有外鍵的 EF Core 表

[英]EF Core table with only foreign key

我有這種情況:

在此處輸入圖像描述

第二個表沒有繼承第一個表。 它將包含不同的信息

我正在使用 EF Core,但無法為這兩個實體配置模型。 我使用流暢的 API 配置並使用 EF Core Migrations 創建表。 型號及其配置如下:

public class Table1 
{
    public long Id { get; set; }
    public string FirstName { get; set; }

    public List<Table2> T2 { get; set; }
}

public class Table1Configuration : IEntityTypeConfiguration<Table1>
{
    public void Configure(EntityTypeBuilder<Table1> builder)
    {
        builder.ToTable("table1");

        builder.Property(s => s.Id)
            .HasColumnName("id")
            .HasColumnType("serial");

        builder.Property(s => s.FirstName)
            .HasColumnName("first_name");
    }
}

第二個:

public class Table2 
{
    public long Table1Id { get; set; }
    public DateTime Timestamp { get; set; }
    public double Value { get; set; }

    public Table1 T1 { get; set; }

}

public class Table2Configuration : IEntityTypeConfiguration<Table2>
{
    public void Configure(EntityTypeBuilder<Table2> builder)
    {
        builder.ToTable("table2");

        builder.Property(s => s.Table1Id)
            .HasColumnName("table1_id");
        builder.HasNoKey();

        builder.Property(s => s.Timestamp)
            .HasColumnName("ts");

        builder.Property(s => s.Value)
            .HasColumnName("value");

        builder.HasOne(s => s.T1)
            .WithMany(s => s.T2)
            .HasForeignKey(s => s.Table1Id);
    }
}

當我運行Update-Database命令時,它會引發異常:

System.Reflection.TargetInvocationException:調用的目標已引發異常。
System.InvalidOperationException:無法添加導航“”,因為它以無鍵實體類型“Table2”為目標。 導航只能針對帶有鍵的實體類型。

我們怎樣才能有一個只有外鍵的表? 我不想為主鍵添加額外的列,因為第二個表會被頻繁刷新

如果我錯過了一些有用的信息,請讓我在評論中加入!

在此先感謝,朱利安

正如@Bryan Lewis 在評論中建議的那樣,任何人都會遇到同樣的問題,我剛剛在表中添加了一個主鍵

暫無
暫無

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

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