【问题标题】:EF Core table with only foreign key只有外键的 EF Core 表
【发布时间】:2020-07-24 05:49:34
【问题描述】:

我有这种情况:

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

我正在使用 EF Core,但我无法为这两个实体配置模型。我使用流畅的 API 配置并使用 EF Core 迁移来创建表。型号及其配置如下:

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”为目标。导航只能定位带有键的实体类型。

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

如果我错过了一些有用的信息,请让我加入 cmets!

提前致谢, 朱利安

【问题讨论】:

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


【解决方案1】:

正如@Bryan Lewis 在评论中建议的那样,任何人都遇到了同样的问题,我刚刚在表中添加了一个主键

【讨论】:

    猜你喜欢
    • 2019-06-23
    • 2020-10-03
    • 2021-11-14
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多