C# 如果映射不存在,则首先使用EF核心代码获取错误
大家好,我有下面这样的模型C# 如果映射不存在,则首先使用EF核心代码获取错误,c#,entity-framework,entity-framework-core,ef-code-first,ef-code-first-mapping,C#,Entity Framework,Entity Framework Core,Ef Code First,Ef Code First Mapping,大家好,我有下面这样的模型部分 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 des
部分
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
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
我还有一个模型请求
,模型如下所示
sectionId Name description
1 code1 code 1
2 code2 code 2
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
下面是请求模型的示例数据结构
sectionId Name description
1 code1 code 1
2 code2 code 2
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
modelBuilder.Entity()
.HasOne(a=>a.sections)
.有一个(o=>o.Requests)//不确定这是否是将这两个模型映射为“请求模型”中列出的一对多映射的正确方法
上面提到的映射是实现相同目标的正确方法,我使用的是实体框架核心代码优先的方法
如果不使用上述映射,则会出现以下错误:
无法确定请求.sections
和sections.Requests
之间的一对一关系的子/从属方
有人能告诉我是否有其他方法可以映射这两个模型吗
modelBuilder.Entity<sections>()
.HasOne(a => a.Requests)
modelBuilder.Entity()
.HasOne(a=>a.Requests)
请求的示例数据显示部分
和请求
之间的关系是一对多(例如,有两个请求的部分ID==1
)
因此,当前的参考导航属性
public Requests Requests { get; set; }
public ICollection<Requests> Requests { get; set; }
这意味着一对一应成为集合导航属性
public Requests Requests { get; set; }
public ICollection<Requests> Requests { get; set; }
这样,您将遵循EF核心约定,并且在大多数情况下不需要数据注释/流畅配置
参考:我正在寻找一对多的关系。。在requests表中会有更多的部分,如我在requests表中所示。非常感谢您的详细解释,对于这两个模型映射,我不需要在db context rightRight下编写任何外部映射。即使您不使用迁移,也可以始终
添加迁移
来创建临时迁移,并查看(在Up
方法中)EF Core如何将实体模型映射到数据库(以及完成后删除迁移
)。