过滤导航属性实体框架,返回NULL

时间:2013-10-22 17:11:08

标签: c# asp.net-mvc entity-framework entity-framework-5

我正在尝试使用导航属性但是当我使用它时,我收到错误

  

值不能为空。

这是可以理解的,因为People集合是NULL,但为什么它是NULL?

我真正要做的是通过RequestorPersonID选择Requestor的名称(最后一个代码片段的最后一行)

public abstract class Person
{
    [Key]     
    public int PersonID { get; set; }         
    public string FirstName { get; set; }      
} 
public class Employee : Person
{
    public string Department { get; set; }
}
public class FrDetail
{
    [Key]
    public int FrID { get; set; }      
    public int RequestorPersonID { get; set; }
    virtual public IList<Person> People { get; set; }
}
public class EFDbContext : DbContext
{      
       public DbSet<Person> People { get; set; }
       public DbSet<Employee> Employees { get; set; }
       public DbSet<FrDetail> FrDetails { get; set; }    
} 

public ViewResult List()
{
    EFDbContext context = new EFDbContext();
    IQueryable<FrDetail> frDetails = context.FrDetails.Include(x => x.People);
    return View(frDetails);
}

//The view

@model IQueryable<FrDetail>   
@foreach (var p in Model)
    Html.RenderPartial("FunctionRequestSummary", p);
}

//Partial View FunctionRequestSummary

@model FrDetail
@Model.People.Count()//IT'S ALWAYS ZERO
//@Model.People//NULL
@Model.People.Where(x=>x.PersonID==Model.RequestorPersonID).FirstOrDefault().FirstName

问题出在计数始终为0的最后一行。我试过切换

  

ProxyCreationEnabled = false;和LazyLoadingEnabled = false;

这也无济于事。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

public abstract class Person
{
    [Key]     
    public int PersonID { get; set; }         
    public string FirstName { get; set; }      
} 
public class Employee : Person
{
    public string Department { get; set; }
}
public class FrDetail
{
    [Key]
    public int FrID { get; set; }      
    public virtual Person RequestorPerson { get; set; }
}
public class EFDbContext : DbContext
{      
       public DbSet<Person> People { get; set; }
       public DbSet<Employee> Employees { get; set; }
       public DbSet<FrDetail> FrDetails { get; set; }    
} 

public ViewResult List()
{
    EFDbContext context = new EFDbContext();
    IQueryable<FrDetail> frDetails = context.FrDetails;
    return View(frDetails);
}

//The view

@model IQueryable<FrDetail>   
@foreach (var p in Model)
{
    Html.RenderPartial("FunctionRequestSummary", p);
}

//Partial View FunctionRequestSummary

@model FrDetail
@Model.RequestorPerson.FirstName