代码之家  ›  专栏  ›  技术社区  ›  erhan355

与Asp一起使用时,实体框架显示出不一致的行为。net标识

  •  0
  • erhan355  · 技术社区  · 9 年前

    我有3个表分别是Violation、Comment和自动生成的AspNetUsers。它们之间的关系如下。

    enter image description here

    我使用代码优先的方法,我的模型如下。为了简洁起见,删除了一些属性。

    违规模型

    public class Violation
        {
            public Violation()
            {
                this.Comments = new HashSet<Comment>();
            }
            public int Id { get; set; }
            public virtual ICollection<Comment> Comments { get; set; }
            public virtual ApplicationUser CreatorUser { get; set; }
        }
    

    注释模型

     public class Comment
        {
    
            public int Id { get; set; }
            [Required]
            public string Content { get; set; }
            [Required]
            public DateTime PostedDateTime { get; set; }
            public ApplicationUser ApplicationUser { get; set; }
    
            public Violation Violation { get; set; }
    
        }
    

    ApplicationUser(AspNetUsers表)

     public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
        {
            this.Comments = new List<Comment>();
            this.Violations = new List<Violation>();
    
        }
        public virtual List<Comment> Comments { get; set; }
        public virtual List<Violation> Violations { get; set; }
    }
    

    问题是,当我尝试检索Comment的ApplicationUser导航属性时,我看到其中许多属性指向空属性,即使数据库中每个属性都有正确的记录。

    很快,EF无法正确检索数据库记录。我坚持了下来,找不到原因。

    Exception

    enter image description here enter image description here

    2 回复  |  直到 9 年前
        1
  •  2
  •   Chris Pratt    9 年前

    事实上,这是 懒洋洋的。你没有添加 virtual 您的关键字 Comment.ApplicationUser 属性,因此实体框架无法重写它以添加延迟加载逻辑。因此,除非显式加载,否则它总是为空。添加 事实上的 关键字,你会没事的。

        2
  •  1
  •   Steve Greene    9 年前

    如果要填充导航属性,则需要将其包含在查询中:

    var comments = context.Comments
      .Include(c => c.Violation)
      .Include(c => c.ApplicationUser)
      .Where(x => x.Violation.Id == violationId);
    

    https://msdn.microsoft.com/en-us/data/jj574232.aspx#eager