虚拟列表未在EF6中填充

时间:2016-01-28 12:24:27

标签: asp.net-mvc-4 entity-framework-6

虚拟列表未填充第二行数据。 这是我的userprofile模型

  [Table("UserProfile")]
   public class USRProfile
    {
        [Key]
        public int UserId { get; set; }
        [Required]
        public string UserName { get; set; }
        public int? IntroducerId { get; set; }
        [ForeignKey("IntroducerId")]
        public virtual USRProfile Introducer { get; set; }
        public virtual List<UserInRole> UserInRoles { get; set; }
        public virtual List<USRProfile> Members { get; set; }

    }

和我的userinrole模型

 [Table("webpages_UsersInRoles")]
    public class UserInRole
    {
        [Key]
        public int RoleId { get; set; }
        [ForeignKey("RoleId")]
        public virtual UserRole UserRole { get; set; }
        public int UserId { get; set; }
        [ForeignKey("UserId")]
        public virtual USRProfile User { get; set; }
    }

这是我的获取用户的查询

  public JsonResult GetUser(int id)
            {
                var usr = uRepository.USRProfiles.FirstOrDefault(c => c.UserId == id);
                var seconusrrole = usr.Members[1].UserInRoles;
                //here seconusrrole is null, but called individually it get data.
                return Json(, JsonRequestBehavior.AllowGet);
            }

这是一个错误,或者我做错了什么?

1 个答案:

答案 0 :(得分:0)

您没有加载相关实体

// using System.Data.Entity.Core.Objects;
var usr = uRepository.USRProfiles.Include(x => x.Members.Select(y => y.UserInRoles))
                                 .FirstOrDefault(c => c.UserId == id);

var seconusrrole = usr.Members[1].UserInRoles;

有关详细信息,请参阅Microsoft帖子:https://msdn.microsoft.com/en-ca/data/jj574232.aspx

修改

您必须添加&#34; System.Data.Entity.Core.Objects&#34;要包含表达式的命名空间。

include方法是IQueryable&lt; T&gt;上的扩展方法。