c# - 如果首先使用 EF 核心代码映射不存在,则会出现错误

标签 c# entity-framework entity-framework-core ef-code-first ef-code-first-mapping

大家好,我有像下面这样的模型 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 and Sections.Requests.

如果有任何其他方法可以映射这两个模型,请告诉我

最佳答案

Requests 的示例数据表明,SectionRequest 之间的关系是一对(例如,有 2使用 SectionId == 1 请求)。

所以当前引用导航属性

public Requests Requests { get; set; }

这意味着一对一对应该成为集合导航属性

public ICollection<Requests> Requests { get; set; }

现在您可以使用HasOne + WithManyHasMany + 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/

相关文章:

c# - 如何使用 log4net 记录 EF 生成的 SQL

c# - Entity Framework 核心计算属性多个表

c# - 如何根据 XUnit 测试隔离 EF InMemory 数据库

c# - 如何同步使用 UserManager?

c# - 如何跟踪 Entity Framework 中更新了哪些实体

c# - 当 ApiController 还需要空构造函数时使用依赖注入(inject)?

c# - Id 属性的 Entity Framework 虚拟属性和数据库访问?

c# - 忽略数据模型中的属性,同时将它们保留在 EF Core 迁移中

c# - 每小时整点执行方法

c# - ComboBox 填充 DataSource 很慢