仅有外键的EF Core表

时间:2020-04-11 13:56:17

标签: c# .net-core entity-framework-core entity-framework-migrations

我有这种情况:

enter image description here

第二个表没有继承第一个表。它将包含不同的信息

我正在使用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'。导航只能使用键来定位实体类型。

我们怎么有一个只有外键的表?我不想为主键添加额外的列,因为第二个表将被频繁刷新

如果我错过了一些对您有所帮助的信息,请让我将其包含在评论中!

预先感谢, 朱利安

1 个答案:

答案 0 :(得分:0)

由于有人偶然发现了同样的问题,正如@Bryan Lewis在评论中建议的那样,我刚刚在表中添加了主键

相关问题