Entity Framework 7 自引用 table 返回 null

Entity Framework 7 self referencing table returning null

我在 MVC 6 Web 应用程序中使用 EF 7 (beta6-13679)(由于需要 AD 集成,所以只有 dnx 4.5.1),采用数据库优先方法,无法获得自引用 table 到 return 一个正确的值,当 运行 我的应用程序时我总是得到空值,但是 LINQPad 发现并使用 parent/children 就好了。想知道是不是我做错了什么,或者这是否是新 EF 中的错误。希望有人可以复制这个问题,或者更好的是,解决它。 :) 抱歉无法嵌入图像,我还不允许。

这是模型:

public partial class Directories
{
    public Directories()
    {
        Directory_ACL_Entries = new HashSet<Directory_ACL_Entries>();
        Files = new HashSet<Files>();
    }

    public long Directory_ID { get; set; }
    public DateTime Created { get; set; }
    public DateTime Discovery_TS { get; set; }
    public string Hash { get; set; }
    public bool Hidden { get; set; }
    public long? Parent_Directory_ID { get; set; }
    public string Path { get; set; }

    public virtual ICollection<Directory_ACL_Entries> Directory_ACL_Entries { get; set; }
    public virtual ICollection<Files> Files { get; set; }
    public virtual Directories Parent_Directory { get; set; }
    public virtual ICollection<Directories> InverseParent_Directory { get; set; }
}

这是 EF 流畅的代码:

modelBuilder.Entity<Directories>(entity =>
        {
            entity.HasKey(e => e.Directory_ID);

            entity.HasIndex(e => e.Hash).HasName("UK_Directories").IsUnique();

            entity.Property(e => e.Created).HasColumnType("datetime");

            entity.Property(e => e.Discovery_TS).HasColumnType("datetime");

            entity.Property(e => e.Hash)
                .IsRequired()
                .HasMaxLength(50);

            entity.Property(e => e.Path).IsRequired();

            entity.HasOne(d => d.Parent_Directory).WithMany(p => p.InverseParent_Directory).HasForeignKey(d => d.Parent_Directory_ID);
        });

这是使用逆向工程脚手架通过以下命令自动生成的:

dnx ef dbcontext scaffold "Server=serverName\SQLEXPRESS;Database=dbName;Trusted_Connection=True;" EntityFramework.MicrosoftSqlServer --outputDir Models

LINQPad 正确显示父值 returning: LINQPad showing parent and children

Visual Studio 返回空: VS returning null

可能是因为 LinqPad 使用 Linq to SQL,这是它在创建连接时使用的默认数据上下文。如果您想在 LinqPad 中使用 EF 7,则需要下载其驱动程序:

步骤

  1. 去添加连接
  2. 单击查看更多驱动程序... 按钮
  3. 安装 EF 7 驱动程序(最适合 LINQPad 5.06 或更高版本)
  4. 使用它来建立与您的数据库的连接。

现在,正如@bazz 指出的那样,EF7 不支持延迟加载,因此您必须通过 Include 方法使用预先加载来加载这些相关实体作为查询的一部分:

var result=Directories.Include(d=>d.Children)...;