【问题标题】:EF Core code first migration: "The child/dependent side could not be determined for the one-to-one relationship"EF Core 代码首次迁移:“无法确定一对一关系的子/依赖方”
【发布时间】:2020-12-03 02:53:49
【问题描述】:

我正在执行代码优先迁移到我的 PostgreSQL 数据库。我已经根据我看到的一些示例配置了我的关系,但我对下面的错误感到困惑。

抛出异常:Microsoft.EntityFrameworkCore.dll 中的“System.InvalidOperationException” Microsoft.EntityFrameworkCore.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理 无法确定“ecommercecontent.identification”和“ecommercecontentidentification.ecommercecontent”之间的一对一关系的子/依赖方。要识别关系的子/依赖方,请配置外键属性。如果这些导航不应该是同一关系的一部分,请在不指定相反的情况下配置它们。详情请见http://go.microsoft.com/fwlink/?LinkId=724062

我的代码示例如下,为简洁起见,删除了一些内容。

以下是有问题的两个类:

public class ecommercecontent
{
    [Key]
    public int ecommercecontentid { get; set; }

    public string productnameenglish { get; set; }

    public string productnamefrench { get; set; }

    public string brandnameenglish { get; set; }

    public string brandnamefrench { get; set; }

    public ecommercecontentidentification identification { get; set; }
}

public class ecommercecontentidentification
{
    [Key]
    public int ecommercecontentidentificationid { get; set; }

    public DateTimeOffset archivedate { get; set; }

    public DateTimeOffset dateupdated { get; set; }

    public DateTimeOffset startdate { get; set; }

    public DateTimeOffset systemversion { get; set; }

    public ecommercecontent ecommercecontent { get; set; }
}

这是我的 DbContext 类,带有 OnModelCreating 覆盖:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ecommercecontent>()
        .HasOne(a => a.identification)
        .WithOne(b => b.ecommercecontent)
        .OnDelete(DeleteBehavior.Cascade);
}

有什么想法我在这里做错了吗?

【问题讨论】:

  • 您可以从关系的任一侧开始定义.HasOne(...).WithOne(...).HasForeignKey&lt;T&gt;(...) 告诉流利的 api 哪个是主要的,哪个是依赖的。

标签: c# postgresql entity-framework-core


【解决方案1】:

当你有一对一的关系时,你需要告诉 EF 哪个是依赖关系。比如ecommercecontentidentification是依赖,那么就需要加上这一行。

 modelBuilder.Entity<ecommercecontent>()
        .HasOne(a => a.identification)
        .WithOne(b => b.ecommercecontent)
        .HasForeignKey<ecommercecontentidentification>(e => e.{{foriegn key property}})
        .OnDelete(DeleteBehavior.Cascade);

我不知道这两个表之间共享什么键。您的ecommercecontentidentification 需要有ecommercecontentid,反之亦然。

【讨论】:

  • 成功了。我按照您的建议添加了新字段(ecommercecontentidentification.ecommercecontentid),然后使用 HasForeignKey 方法选择该新字段作为外键。
猜你喜欢
  • 2019-08-22
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
相关资源
最近更新 更多