与EFCore 2.1的一对一关系

时间:2018-06-14 22:10:39

标签: c# entity-framework-core

以下代码正在使用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");
});

我该如何解决这个问题?我已尝试过所有HasOneWithOneHasForeignKey组合,似乎没有任何效果......

2 个答案:

答案 0 :(得分:1)

通过查看您的模型,我认为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");
});

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

答案 1 :(得分:1)

我已经通过添加OwnsOne解决了它:

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

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