EF Core拥有的实体需要一个主键。

4

在使用 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仍然需要定义主键。
1个回答

0
我刚刚遇到了同样的问题。对我来说,问题是在EntityTypeConfiguration类中有一个带有依赖注入的构造函数。当我移除构造函数(并注释掉需要注入服务的那一行)时,一切都正常工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接