none
导航属性查询出来为空 RRS feed

  • 问题

  • 我添加了3张表 User、Role、UserRole(User和Role的中间表)

    1.添加员工

     public ActionResult Add(User user)
            {
                if (ModelState.IsValid)
                {
                    var entity = db.Users.FirstOrDefault(p => p.No == user.No);//No为主键
                    if (entity != null)
                    {
                        return Content("该员工已存在");
                    }
                    db.Users.Add(user);
                    db.SaveChanges();
                    return Content("addOk");
                }
                return Content("验证失败");
            }

    2.添加角色

      public ActionResult Add(RoleModel model)
            {
                if (ModelState.IsValid)
                {
                    Role role = new Role();
                    role.No = model.No;//No为主键
                    role.Name = model.Name;
                    role.Makings = model.Makings;
                    role.DutyReq = model.DutyReq;
                    role.CreateTime = DateTime.Now;
                    db.Roles.Add(role);
                    db.SaveChanges();
                    return Content("ok");
                }
                return Content("falair");

    3,添加中间表数据

     public ActionResult AddUserRole(string roleNo, string userNo)
            {
                UserRole userRole = new UserRole();主键为Id
                userRole.RoleNo = roleNo;//外键
                userRole.UserNo = userNo;//外键
                db.UserRoles.Add(userRole);
                db.SaveChanges();
                return Content("添加成功");
            }

    当我使用如下语句查询时

      var roles = db.Roles.Include("UserRoles").ToList();

    roles变量里面的导航属性UserRoles为空

    2015年9月21日 6:34

答案

  • 你好,

    看上去像是lazy loading的问题。默认情况下lazy loading是打开的,所以外键对应的内容是null。请尝试在初始化完context对象后设置lazy loading为false后,在试试能不能读出内容。

    db.Configuration.LazyLoadingEnabled = false;

    关于lazy loading更多请看: https://msdn.microsoft.com/en-us/data/jj574232.aspx#lazy


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2015年9月22日 2:16

全部回复