【发布时间】: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!
提前致谢, 朱利安
【问题讨论】:
-
无密钥实体在 EF 中有很大的限制(请参阅 docs.microsoft.com/en-us/ef/core/modeling/keyless-entity-types)。我建议只添加主键。没有它你就不能有导航。
标签: c# .net-core entity-framework-core entity-framework-migrations