大家好,我有像下面这样的模型 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; }
}
请求模型的示例数据结构如下所示
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
上面提到的映射是否是实现相同目的的正确方法,我正在使用 Entity Framework 核心代码优先方法。
如果我不使用上面的映射,我会得到这个错误:
The child/dependent side could not be determined for the one-to-one relationship between
Requests.sections
andSections.Requests
.
如果有任何其他方法可以映射这两个模型,请告诉我
最佳答案
Requests 的示例数据表明,Section
和 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 约定,并且在大多数情况下不需要数据注释/流畅的配置。
引用: Relationships
关于c# - 如果首先使用 EF 核心代码映射不存在,则会出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58945687/