簡體   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