繁体   English   中英

实体框架7自引用表返回null

[英]Entity Framework 7 self referencing table returning null

我在MVC 6 Web应用程序中使用EF 7(beta6-13679)(由于需要AD集成,因此仅dnx 4.5.1),采用数据库优先方法,无法获取自引用表来正确返回值,我在运行我的应用程序时,总是会返回null,但是LINQPad可以找到并与父/子一起工作。 想知道我是否有问题,或者这是否是新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显示父级值正确返回: LINQPad显示父级和子级

Visual Studio返回Null: VS返回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)...;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM