2012-11-23 217 views
5

我有簡單的叫OdeToFoodDb的DbContext類:實體框架空對象

public class OdeToFoodDb: DbContext 
{ 
    public DbSet<Restaurant> Restaurants { get; set; } 
    public DbSet<Review> Reviews { get; set; } 

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Restaurant>() 
      .HasMany(resturant => resturant.Reviews) 
      .WithRequired(review => review.Resturant); 
     base.OnModelCreating(modelBuilder); 
    } 
} 

和類定義:

public class Restaurant 
{ 
    //public virtual int ID { get; set; } 
    public virtual int RestaurantId { get; set; } 
    public virtual string Name { get; set; } 
    public virtual Address Address { get; set; } 
    public virtual IList<Review> Reviews { get; set; } 
} 

public class Review : IValidatableObject 
{ 
    public int ReviewId { get; set; } 

    [DisplayName("Digning Date")] 
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)] 
    [DataType(DataType.Date)] 
    public DateTime Created { get; set; } 

    [Range(1, 10)] 
    public int Rating { get; set; } 

    [Required] 
    [DataType(DataType.MultilineText)] 
    public string Body { get; set; } 
    public int RestaurantId { get; set; } 
    public Restaurant Resturant { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     var fields = new[]{ "Created"}; 

     if(Created > DateTime.Now) 
     { 
      yield return new ValidationResult("Created date cannot be in the future.", fields); 
     } 

     if (Created < DateTime.Now.AddYears(-1)) 
     { 
      yield return new ValidationResult("Created date cannot be to far in the past.", fields); 
     } 
    } 
} 

我的問題是,當我從的DbContext選擇這樣的評論:

OdeToFoodDb _db = new OdeToFoodDb(); 
    public PartialViewResult LatestReview() 
    { 
     var review = _db.Reviews.FindTheLatest(1).Single(); 
     //************************************ 
     return PartialView("_Review", review); 
    } 

我檢查了review.Restaurant是空的!而其他財產具有價值。我的代碼有什麼問題?

+0

您是否錯過了包含查詢中的Restaurant對象?我不確定FindTheLatest在做什麼,但應該是_db.Reviews.Include(r => r.Restaurant).FindTheLatest(1).Single()或_db.Reviews.Include(「Restaurant」)。FindTheLatest(1 ).Single() – Khepri

+0

@Khepri我是新來的實體框架。你能說說'包括'方法嗎? –

+0

包含在結果中加載導航屬性。如果您不包含該語句,則不填充導航屬性的結果。 – Khepri

回答

8

要麼負荷導航屬性明確通過Include方法Restaurant

var review = _db.Reviews.Include(r => r.Restaurant).FindTheLatest(1).Single(); 

,或者您可以啓用延遲加載該屬性,通過使虛擬:

public virtual Restaurant Restaurant { get; set; } 

你可以閱讀更多有關加載相關實體here

+1

我用第二種方法,它工作正常。 –

+0

你能告訴我在上面的代碼中,關鍵字'虛擬'是什麼? –

+1

@SeyedMortezaMousavi:在任何實體類型的'virtual'屬性中,當使用該實體類型的實例時,是上下文創建動態代理的標記。特別是,對於導航屬性,這意味着該上下文會提供延遲加載 - 當您調用屬性getter時,代理對象將加載屬性值並返回結果。我已經添加了一個答案的鏈接。 – Dennis