2013-10-22 86 views
0

我試圖使用導航屬性,但是當我使用它,我得到一個錯誤過濾導航屬性實體框架,返回NULL

值不能爲空。

這是可以理解的,因爲People集合是NULL,但它爲什麼是NULL?

我真正想要做的是通過RequestorPersonID選擇請求者的名稱(最後的代碼段的最後一行)

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;

這也沒有幫助。我錯過了什麼嗎?

回答

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 
+0

我試過ICollection和IList沒有成功。 Model.People仍爲NULL –

+0

您是否使用ICollection進行代理創建並啓用了延遲加載? – grin0048

+0

我已經嘗試啓用和禁用。沒有運氣 –