首页 > 解决方案 > 与 EFCore 2.1 的一对一关系

问题描述

以下代码适用于 EFCore 2.0。

自 2.1 更新以来,我遇到了一个阻塞错误:

The child/dependent side could not be determined for the one-to-one relationship 
between 'Entity2.Main' and 'Entity1.Metadata'. 
To identify the child/dependent side of the relationship, configure the foreign key property. 
If these navigations should not be part of the same relationship configure them without specifying 
the inverse. See http://go.microsoft.com/fwlink/?LinkId=724062 for more details.

这些表类似于(它们共享相同的 id,但在不同的表上):

Table_Entity1:
- Id
- Name
- Description

Table_Entity2:
- Id
- Flag1
- Flag2

实体如下:

public class Entity1
{
    public long Id {get;set;}
    public string Name {get;set;}
    public string Description {get;set;}
    public Entity2 Metadata {get;set;}
}

public class Entity2
{
    public long Id {get;set;}
    public bool Flag1 {get;set;}
    public bool Flag2 {get;set;}
    public Entity1 Main {get;set;}
}

它们声明如下:

builder.Entity<Entity1>(b =>
{
    b.HasKey(e => e.Id);
    b.Property(e => e.Id).ValueGeneratedNever();
    b.HasOne<Entity2>(e => e.Metadata)
        .WithOne(e => e.Main)
        .HasForeignKey<Entity2>(e => e.Id)
        .HasPrincipalKey<Entity1>(e=>e.Id); 
    b.ToTable("Table_Entity1");
});

builder.Entity<Entity2>(b =>
{
     b.HasKey(e => e.Id);
     b.ToTable("Table_Entity2");
});

我该如何解决这个问题?我已经尝试了所有HasOne, WithOne,HasForeignKey组合,似乎没有任何效果......

标签: c#entity-framework-core

解决方案


通过查看您的模型,在我看来,它Entity 1拥有Entity 2. 您是否遵循了 Microsoft 文档拥有的实体类型部分中的建议:https ://docs.microsoft.com/en-us/ef/core/modeling/owned-entities ?

您可以尝试将模型更改为:

public class Entity2
{
    public bool Flag1 { get; set; }
    public bool Flag2 { get; set; }
}

public class Entity1
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public Entity2 Metadata { get; set; }
}

然后在配置上:

builder.Entity<Entity1>(b =>
{
    b.HasKey(e1 => e1.Id);
    b.OwnsOne(e1 => e1.Metadata, md => {

        // I think the example on the Microsoft Doc is wrong but need to verify.
        // I opened an issue here: 
        //   https://github.com/aspnet/EntityFramework.Docs/issues/772

        md.ToTable("Table_Entity2");
    });

    b.ToTable("Table_Entity1");
});

免责声明:我手工写了任何东西,因此它们没有经过测试。


推荐阅读