c# - 如果不存在与 EF 核心代码的映射,则会出现错误
问题描述
大家好,我有sections
下面这样的模型
public class Sections
{
public int SectionId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Requests Requests { get; set; }
}
部分模型的数据结构如下所示
sectionId Name description
1 code1 code 1
2 code2 code 2
我还有一个模型Requests
,模型如下所示
public class Requests
{
public int RequestId { get; set; }
public string Description { get; set; }
public int SectionId { get; set; }
public Sections sections { get; set; }
}
以及 Requests 模型的示例数据结构,如下所示
RequestId Description SectionId
1 test1 1
2 test2 1
3 test1 2
4 test2 2
使用这种模型数据结构,我在下面映射这两个模型
modelBuilder.Entity<Requests>()
.HasOne(a => a.sections)
.WithOne(o => o.Requests); //not sure if this is correct way to map these two models with one-to-many mapping as listed in requests model
是上面提到的映射是实现相同的正确方法,我使用的是实体框架核心代码优先方法。
如果我不使用上述映射,我会收到此错误:
Requests.sections
无法确定和之间的一对一关系的子/依赖方Sections.Requests
。
任何人都可以让我知道是否有任何其他方式来映射这两个模型
解决方案
Section
Requests 的示例数据显示和之间的关系Request
是一对多的(例如,有 2 个请求带有SectionId == 1
)。
所以当前引用的导航属性
public Requests Requests { get; set; }
这意味着一对一应该成为集合导航属性
public ICollection<Requests> Requests { get; set; }
现在您可以使用HasOne
+WithMany
或HasMany
+WithOne
来配置关系。但这很可能不是必需的,因为通常 EF Core 通常可以确定一对多关系。
因此,虽然不是强制要求,但最好为实体和引用导航属性使用单数名称,为集合导航属性使用复数名称:
public class Section
{
public int SectionId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<Request> Requests { get; set; }
}
public class Request
{
public int RequestId { get; set; }
public string Description { get; set; }
public int SectionId { get; set; }
public Section Section { get; set; }
}
这样,您将遵循 EF Core 约定,并且在大多数情况下不需要数据注释/流畅的配置。
参考: 关系
推荐阅读
- botframework - MS Teams 频道上的 Adaptivecard maxActions 限制
- python - 字符串减去字符串对python不好
- angular - 如何初始化角管道(CurrencyPipe)
- c - 将 hh:mm:ss 添加到 12 小时时间格式
- python - 为什么 Leetcode 不接受“Missing Number (Problem no:268)”问题的解决方案?
- android - 谷歌地图自动设置给定地点的标签
- google-bigquery - 按 ID 分组行并创建数组字段 - GoogleSQL
- wordpress - wp_mail 不以 HTML 格式发送电子邮件
- android - 如何创建可绘制的右动画按钮
- linux - 为什么 Linux shell 中带大括号的 `{cat,filename}` 组命令可以工作?