c# - 与 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/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");
});
免责声明:我手工写了任何东西,因此它们没有经过测试。
推荐阅读
- php - laravel + mongo + gpaphql 获取子数组
- python-3.x - 如何在项目目录中获取 Python 文件的真实路径
- if-statement - XSLT 2.0:通过匹配一个子节点并比较其他子节点来获取 XML 节点
- sas - 将新的空行添加到具有来自另一个表的名称的 SAS 表
- java - 如何使用无 XML 的 Spring Web 应用程序设置 JBoss Wildfly 上下文根?
- pytorch - 评估 GAN 的 Parzen 窗口对数似然
- javascript - findAll() 不是 sequelize 中的函数
- c++ - 对递增两个变量的嵌套 FOR 循环进行故障排除
- emacs - 如何在 org 模式下预览较小的图像?
- r - 如何知道数据是否在使用 r 的生存分析中被审查