在使用 EF Core 7 时遇到了一个问题,它要求拥有的实体必须有一个主键。
我已经阅读了 Microsoft 的 Owned Entity Type 文档,甚至他们的示例也要求有一个主键。
当尝试创建迁移时,使用以下命令:
dotnet ef migrations add "Project Init"
我遇到了以下错误:
下面是具有三个属性的父类,它们使用相同的拥有类(SegmentPoint)。必须定义主键,才能使用实体类型“SegmentPoint”
//BaseDomain contains the Id property
public class Segment : BaseDomain
{
public string Name { get; private set; }
public SegmentPoint PointOne { get; private set; }
public SegmentPoint? PointTwo { get; private set; }
public SegmentPoint? PointThree { get; private set; }
//Removed
}
这是拥有的类
public class SegmentPoint
{
public PointType? Type { get; internal set; }
public string? Label { get; internal set; }
public string? Format { get; internal set; }
}
在Segment
的实体配置中,我已经包含了所有三个属性的OwnsOne
和列重命名。
我没有SegmentPoint
的实体配置。
internal class SegmentConfig : IEntityTypeConfiguration<Segment>
{
public void Configure(EntityTypeBuilder<Segment> builder)
{
builder.ToTable("ReportSegment");
builder.HasKey(b => b.Id);
builder.HasOne(b => b.Report)
.WithMany(r => r.Segments);
builder.OwnsOne(
b => b.PointOne,
sa =>
{
sa.Property(p => p.Label).HasColumnName("PointOneLabel");
sa.Property(p => p.Format).HasColumnName("PointOneFormat");
sa.Property(p => p.Type).HasColumnName("PointOneType");
});
builder.OwnsOne(b => b.PointTwo,
sa =>
{
sa.Property(p => p.Label).HasColumnName("PointTwoLabel");
sa.Property(p => p.Format).HasColumnName("PointTwoFormat");
sa.Property(p => p.Type).HasColumnName("PointTwoType");
});
builder.OwnsOne(b => b.PointThree,
sa =>
{
sa.Property(p => p.Label).HasColumnName("PointThreeLabel");
sa.Property(p => p.Format).HasColumnName("PointThreeFormat");
sa.Property(p => p.Type).HasColumnName("PointThreeType");
});
}
}
有人之前遇到过这种情况吗?我在其他项目中做了许多拥有实体类型,没有像这样的问题。
我尝试从“Segment”实体中删除“PointTwo”和“PointThree”,以查看是否将多个拥有属性映射到单个类会导致问题,但EF Core仍然需要定义主键。