关联属性未加载到实体上

时间:2010-01-11 11:44:58

标签: c# .net entity-framework

我有三个相关实体,最好用这个图描述:

alt text http://thehashtable.com/wp-content/uploads/2010/01/Enttities.png

当我加载用户时,使用以下代码加载User对象,即不为空,但RoleDepartment对象上的Userusing (var productionEntities = new ProductionEntities()) { var userName = GetUserName(); User u = (from usr in productionEntities.UserSet where usr.UserName == userName select usr).FirstOrDefault(); if (u == null) { throw new KpiSecurityException("No local database entry found for user.") { UserName = userName }; } return u.Department.DeptName; } 属性尽管用户数据库记录具有这些关联的有效FK值,但仍为null。

{{1}}

ASIDE:我完成了整个任务,因为ASP.NET MembershipProvider不支持像部门一样的用户“元数据”,我也不得不使用ProfileProvider,巨大的数据库膨胀成本。

2 个答案:

答案 0 :(得分:3)

您必须明确加载此属性

User u = (from usr in productionEntities.UserSet
          where usr.UserName == userName
          select usr).FirstOrDefault();

if (u == null)
{
        throw new KpiSecurityException("No local database entry found for user.") { UserName = userName };
}

if (!u.RoleReference.IsLoaded)
{ u.RoleReference.Load(); }

if (!u.DeparmentReference.IsLoaded)
{ u.DeparmentReference.Load(); }

或在查询中包含此实体

User u = (from usr in productionEntities.UserSet.Include("Role").Include("Department")
          where usr.UserName == userName
          select usr).FirstOrDefault();

答案 1 :(得分:1)

由于您只需要部门名称,只需要project;这样你只需要查询一次数据库:

using (var productionEntities = new ProductionEntities())
{
    var userName = GetUserName();
    var u  = (from usr in productionEntities.UserSet
              where usr.UserName == userName
              select new
              {
                  DeptName = usr.Department.DeptName
              }).FirstOrDefault();
    if (u == null)
    {
        throw new KpiSecurityException("No local database entry found for user.") { UserName = userName };
    }
    return u.DeptName;
}