与Entity Framework 7配置一对多关系的正确方法是什么?

时间:2015-11-19 00:11:13

标签: c# entity-framework-core

我有一个设置,其中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

2 个答案:

答案 0 :(得分:0)

命名约定是具有单个类名,生成的表将是复数形式。尝试将Integrations更改为Integration,将HeaderMaps更改为HeaderMap。你还可以发布你的DbContext代码吗?是否有可能在那里声明HeaderMaps?

答案 1 :(得分:0)

据我所知,问题不在于您的关系配置。您需要使用.Include()

var integration = context.Integrations
     .Include(i => i.HeaderMaps)
     .First(i => i.IntegrationId == 4);

请参阅How to work with collections

相关问题