与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(b => { b.HasKey(e => e.Id); b.Property(e => e.Id).ValueGeneratedNever(); b.HasOne(e => e.Metadata) .WithOne(e => e.Main) .HasForeignKey(e => e.Id) .HasPrincipalKey(e=>e.Id); b.ToTable("Table_Entity1"); }); builder.Entity(b => { b.HasKey(e => e.Id); b.ToTable("Table_Entity2"); }); 

我怎么解决这个问题? 我已经尝试了所有HasOneWithOneHasForeignKey组合,似乎没有任何工作……

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

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

我通过添加OwnsOne解决了这个问题:

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