使用实体框架7配置一对多关系的正确方式是什么
本文关键字:方式 是什么 关系 一对多 实体 框架 配置 | 更新日期: 2023-09-27 18:22:24
我有一个Integration对象有许多HeaderMap对象的设置。类的设置如下所示。当我调用integration.HeaderMaps
时,我得到的返回计数为0,尽管数据库清楚地显示应该有1个结果。我使用的是实体框架7。在一对多的关系中,我缺少什么?
public class Integrations
{
public Integrations()
{
HeaderMaps = new HashSet<HeaderMaps>();
}
[Key]
public int IntegrationId { get; set; }
...
[InverseProperty("Integration")]
public virtual ICollection<HeaderMaps> HeaderMaps { get; set; }
}
public class HeaderMaps
{
[Key]
public int HeaderMapId { get; set; }
public int IntegrationId { get; set; }
[ForeignKey("IntegrationId")]
[InverseProperty("HeaderMaps")]
public virtual Integrations Integration { get; set; }
}
public partial class Dev_IntegrationsContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(@"uid=sa;pwd=******;Initial Catalog=Dev_Integrations; Data Source=*******;Min Pool Size=10;Max Pool Size=150;");
}
public virtual DbSet<HeaderMaps> HeaderMaps { get; set; }
public virtual DbSet<Integrations> Integrations { get; set; }
}
运行时:
var integration = context.Integrations.First(i => i.IntegrationId == 4);
integration.HeaderMaps // returns a count of 0
context.HeaderMaps.First().Integration // there is only 1 row in the table, and it returns an Integrations object with id of 4
SQL:
select * from HeaderMaps where IntegrationId = 4; -- returns 1 record
命名约定是使用单数类名,生成的表将为复数。尝试将Integration更改为Integration,将HeaderMap更改为HeaderMap。你也可以发布你的DbContext代码吗?是否可能没有在其中声明HeaderMaps?
据我所知,问题不在于关系的配置。您需要使用.Include()
var integration = context.Integrations
.Include(i => i.HeaderMaps)
.First(i => i.IntegrationId == 4);
请参阅如何使用集合