EF中对象的局限性

时间:2014-01-31 21:25:08

标签: c# entity-framework object

为什么局部视图会正确显示对象,但调用相同的函数来填充viewmodel会返回null?

类示例模型:

[DisplayColumn("OrganizationName")] 
public class Organization
{
    public  int OrganizationId { get; set; }
    [Display(Name = "Organization Name"), MaxLength(75), Required]
    public  string OrganizationName { get; set; }
    [Display(Name = "Positions")]
    public int? PositionId { get; set; } 
    [Display(Name = "OrganizationSupervisor")]
    public int? OrganizationSupervisorId { get; set; }
    public virtual Organization PrimaryParentOrg { get; set; }
    [Display(Name = "All Positions")]
    public virtual ICollection<Position> OrgPositions { get; set; } 
    [ForeignKey("OrganizationSupervisorId")]
    [InverseProperty("Orgs")]
    public virtual OrganizationSupervisor Supervisor { get; set; } 
}
public class OrganizationSupervisor
{
    [Key]
    public int OrganizationSupervisorId { get; set; }
    [Required]
    public  Position SupervisorPos { get; set; }
    public int? OrganizationId { get; set; }
    [ForeignKey("OrganizationId")]
    public virtual ICollection<Organization> Orgs { get; set; }
}
public class Position
{
    public int PositionId { get; set; }
    public string DefaultTitle { get; set; }    
}

//失败的功能:

public class fcns
{
    private static Position getEmpPosSup(Position EmpPos, Organization Org, ref int Cnt)
    {
        Position PosSup = null;
        Cnt++;
        if ((EmpPos != null) && (Org != null))
        {
            if (Org.Supervisor != null)
                if (Org.Supervisor.SupervisorPos != null)
                    if (EmpPos != Org.Supervisor.SupervisorPos)
                        PosSup = Org.Supervisor.SupervisorPos;
            if (PosSup == null && Cnt < 3)
            {
                //  Try the next level up, up to 3 times then give up
                PosSup = getEmpPosSup(EmpPos, Org.PrimaryParentOrg, ref Cnt);
            }
        }
        return PosSup;
    }
}

该函数返回主管相对于指定组织提交的职位的位置。

1 个答案:

答案 0 :(得分:0)

@BrianLegg

你是对的,谢谢你的建议。问题是延迟加载或类似的东西。我发现似乎总能工作的解决方案是使用存储库函数AllIncluding(...)而不是All函数。例如我用过:

IQueryable<OrganizationSupervisor> lstOrgSups = organizationsupervisorRepository.AllIncluding(organizationsupervisor => organizationsupervisor.SupervisorPos);

这似乎强制EF返回SupervisorPos Position对象,如果在调试会话期间没有询问,则该对象返回null。