实体框架无法将列表加载2级

时间:2018-04-13 10:00:41

标签: c# entity-framework

我有以下模型结构:

技能 意图(SkillId的外键) 话语(IntentId的外键) 插槽(UtteranceId的外键)

意图模型

public class Intent
    {
        [Key]
        public int Id { get; set; }    
        [ForeignKey("Skill")]
        public int? SkillId { get; set; }    
        public string Description { get; set; }           
        public virtual Skill Skill { get; set; }
        public virtual List<Utterance> Utterances { get; set; }
    }

话语模型

   public class Utterance
    {
        [Key]
        public int Id { get; set; }    
        [ForeignKey("Intent")]
        public int IntentId { get; set; }
        public string Utterancetext { get; set; }            
        public virtual Intent Intent { get; set; }
        public virtual List<Slot> Slots { get; set; }
    }

广告位模型

public class Slot
{
    [Key]
    public int Id { get; set; }
    [ForeignKey("Utterance")]
    public int UtteranceId { get; set; }
    public string SlotValue { get; set; }
    public SlotDataTypes SlotDataType { get; set; }        
    public virtual Utterance Utterance { get; set; }
}

实体框架更流畅的API

 modelBuilder.Entity<Intent>()
            .HasOptional(i => i.Skill)
            .WithMany(sk => sk.Intents)
            .HasForeignKey(i => i.SkillId);

        modelBuilder.Entity<Utterance>()
            .HasRequired(x => x.Intent)
            .WithMany(x => x.Utterances)
            .HasForeignKey(x => x.IntentId);

        modelBuilder.Entity<Slot>()
            .HasRequired(x => x.Utterance)
            .WithMany(x => x.Slots)
            .HasForeignKey(x => x.UtteranceId);

在我的数据访问服务中,我有一个方法应该获得Intents&gt;话语&gt;槽。

var intents = ctx.Intents.Include(x => x.Utterances).Include("Utterances.Slots").ToList(); //<-- utterances are populated, slots count is 0
var utterances = ctx.Utterances.Include(x => x.Slots).ToList(); // utterances are populated, slots are populated
var slots = ctx.Slots.ToList(); // slots are populated

        return intents;

第一个电话是我需要的,让我得到所有的意图,他们相关的话语和话语相关的插槽。话语是填充的,但是插槽总是为零,即使数据库中肯定有插槽,第二次调用证明了,因为如果我直接进行话语,并包括插槽,我就会回来。

我在哪里错误地将Intent导航一直到Slots?

1 个答案:

答案 0 :(得分:1)

解决方案是写:

var intents = ctx.Intents.Include(x => x.Utterances.Select(u => u.Slots)).ToList();

在包含集合属性后,调用Select撰写其他包含。