实体框架的Include()方法在某些情况下无法正常工作

时间:2018-10-08 06:32:16

标签: asp.net-mvc entity-framework

Include()方法在以下代码中工作正常:

protected override IQueryable<Relative> GetDbQuery(DbContext dbEnt)
        {
           dbEnt.Configuration.LazyLoadingEnabled = false;

            return base.GetDbQuery(dbEnt)
            .Include(x => x.User.UserSecurity);
        }

但是如果我使用多个包含作为波纹管的话它就不能正常工作。我想问题是两个对象都使用相同的子对象来填充对象。 该方法的结果仅包含Student.User.UserSecurity,但Relative.User.UserSecurity为空。但是,它们都包括在内。  有什么建议吗?

 protected override IQueryable<Relative> GetDbQuery(DbContext dbEnt)
        {
           dbEnt.Configuration.LazyLoadingEnabled = false;

            return base.GetDbQuery(dbEnt)
            .Include(x => x.User.UserSecurity)
            .Include(x => x.StudentsRelativeList.Select(z => z.Student.User.UserSecurity));
        }

我的模型如下:

相对:

public class Relative 
       {
         public Relative()
         {
            StudentsRelativeList = new HashSet<StudentsRelative>();
         }

         [Key,ForeignKey(nameof(User))]
         public Guid Id { get; set; }

         [NotSync]
         public virtual User User { get; set; }

         [NotSync]
         public virtual ICollection<StudentsRelative> StudentsRelativeList 
         {get;set;}
       }

学生:

public class Student  
      {
        [Key,ForeignKey(nameof(User))]
        public Guid Id { get; set; }

        public DateTime RecordDate { get; set; }

        [NotSync]
        public virtual User User { get; set; }
     }

用户:

public class User
     {
        [Key,ForeignKey(nameof(UserSecurity))]
        public Guid Id { get; set; }

        [NotSync]
        public virtual UserSecurity UserSecurity { get; set; }
     }

用户安全性:

public class UserSecurity 
     {
        public Guid Id { get; set; }
        public string FirstName { get; set; }
        public string FirstName { get; set; }
     }

0 个答案:

没有答案