【问题标题】:Entity Framework 7 self referencing table returning null实体框架 7 自引用表返回 null
【发布时间】:2016-04-19 14:55:02
【问题描述】:

我在 MVC 6 Web 应用程序中使用 EF 7 (beta6-13679)(由于需要 AD 集成,仅使用 dnx 4.5.1),采用数据库优先方法,无法获取自引用表来返回值正确地,我在运行我的应用程序时总是得到空值,但是 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 fluent 代码:

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 showing parent and children

Visual Studio 返回 Null: VS returning null

【问题讨论】:

  • this这里,好像EF7不支持懒加载。您将需要使用 Include() 方法。
  • 这确实是问题所在。必须使用以下格式急切地加载自引用列:.Include(table=> table.selfReference)
  • 注意性能! EF7 没有得到很好的优化。我降级了我的项目(从 7 rc1 到 6.3.1),因为性能非常非常糟糕

标签: c# sql-server entity-framework asp.net-core-mvc self-referencing-table


【解决方案1】:

可能是因为 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)...;

【讨论】:

  • 谢谢。正如我在上面对@bazz 的评论中提到的那样,我确实需要急切地加载自引用的列。
猜你喜欢
  • 1970-01-01
  • 2018-12-23
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多