[英]One-to-one relationship with 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
组合,但似乎没有任何效果。
通过查看您的模型,在我看来, Entity 1
拥有Entity 2
。 您是否遵循“ Microsoft文档拥有的实体类型”部分中的建议: https : //docs.microsoft.com/zh-cn/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");
});
免责声明:由于我手写了任何东西,因此未经过测试。
我已经通过添加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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.