实体框架代码中的多列密钥首先使用预先加载

时间:2012-09-09 14:38:53

标签: .net entity-framework ef-code-first many-to-many dbcontext

我使用Entity Framework,我在Users和Boxes之间的数据库中有多对多的关系,如下所示:

public class HistoryEntry
{
    public int BoxId { get; set; }
    public virtual Box Box { get; set; }

    public int UserId { get; set; }
    public virtual User User { get; set; }

    public int ResultBoxId { get; set; }
    public virtual Box ResultBox { get; set; }
}

这个“HistoryEntries”表的键是一个多列键:它包含BoxId和UserId:

        modelBuilder.Entity<HistoryEntry>().HasKey(entry =>
            new
            {
                BoxId = entry.BoxId,
                UserId = entry.UserId
            });

但是,我想关闭延迟加载和代理创建,因为我会使用急切加载的每个查询。

如何以“急切加载”的方式重写我的代码?

1 个答案:

答案 0 :(得分:2)

使用Include方法急切加载导航属性。

var users = context.User.Include(u => u.HistoryEntries.Select(h => h.Box))
      .Where(/* */);