【问题标题】:EF Core 5: Configuring owned type with PK same as FK and with no parent propertyEF Core 5:使用与 FK 相同的 PK 配置拥有的类型且没有父属性
【发布时间】:2021-10-22 03:27:36
【问题描述】:

我正在尝试迁移到 EF Core 5。以前一切正常。我不想更改以下结构。

ActionSetup.cs

public class ActionSetup
{
        public Conditions Conditions { get; set; }
}
public class Conditions
{
       public string SomeValue { get; set; }
}

EntityConfiguration.cs

public class EntityConfiguration: IEntityTypeConfiguration<ActionSetup>
{
        builder.OwnsOne(tah => tah.Conditions, a =>
            {
                a.ToTable("action_conditions");
                a.Property<long>("id");
                a.HasKey("id");
                a.Property(p => p.SomeValue ).HasColumnName("some_value");
            });
}

但是现在,当我尝试获取 ActionSetup 时,我收到一个错误,因为 EF Core 认为我的 FK 被称为 ActionSetupId。我不确定这以前是如何工作的,但有没有办法让它工作,但是:

  • 无需添加单独的 FK。
  • 不在Conditions 类中添加属性?

【问题讨论】:

  • 你是从哪里迁移过来的?例如。 EF6 还是更早的 EF Core 版本?您的数据库中当前存在哪些键/FK?
  • 嗨@Xerillio,我当前的软件包版本是2.2.6。我当前的数据库有一个 PK 也是 FK,名为 id

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


【解决方案1】:

只需将“ActionSetupId”影子属性配置为映射到表中的“id”即可。

modelBuilder.Entity<ActionSetup>()
    .OwnsOne(tah => tah.Conditions, a =>
    {
        a.ToTable("action_conditions");
        a.Property<long>("ActionSetupId").HasColumnName("id");
        a.Property(p => p.SomeValue).HasColumnName("some_value");    
    });

创造

   CREATE TABLE [action_conditions] (
      [id] bigint NOT NULL,
      [some_value] nvarchar(max) NULL,
      CONSTRAINT [PK_action_conditions] PRIMARY KEY ([id]),
      CONSTRAINT [FK_action_conditions_ActionSetup_id] FOREIGN KEY ([id]) REFERENCES [ActionSetup] ([Id]) ON DELETE CASCADE
  );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2021-08-22
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多