使用Entity Framework获取子对象时,父对象为null

时间:2018-04-26 17:19:15

标签: entity-framework entity-framework-6

public class AcsBatchingDbContext : DbContext
{
    public DbSet<CardHolder> CardHolders { get; set; }
    public DbSet<AccessCard> AccessCards { get; set; }
}

public class CardHolder
{
    public int CardHolderId { get; set; }
    public ICollection<AccessCard> AccessCards { get; set; };
}


public class AccessCard
{

    public int AccessCardId { get; set; }
    public CardHolder CardHolder { get; set; }
}

当我尝试获取AccessCards

using (var db = new AcsBatchingDbContext())
{
    var cards = db.AccessCards.ToList();
}

card.CardHolder = null

为什么呢?为什么EF没有抓住CardHolder?

另一个问题:

为什么这个表达式不能编译?

db.AccessCards.Include(x => x.CardHolder).ToList();

为什么唯一的选择是使用

db.AccessCards.Include("CardHolder").ToList();

1 个答案:

答案 0 :(得分:0)

您应该使用include来加载CardHolder实体。

(这需要using System.Data.Entity;

db.AccessCards.Include(x => x.CardHolder).ToList();

或者,您可以像这样申请Include;

db.AccessCards.Include("CardHolder").ToList();