首页 > 解决方案 > 如果不存在与 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

任何人都可以让我知道是否有任何其他方式来映射这两个模型

标签: c#entity-frameworkentity-framework-coreef-code-firstef-code-first-mapping

解决方案


SectionRequests 的示例数据显示和之间的关系Request一对多的(例如,有 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 约定,并且在大多数情况下不需要数据注释/流畅的配置。

参考: 关系


推荐阅读