我有簡單的叫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是空的!而其他財產具有價值。我的代碼有什麼問題?
您是否錯過了包含查詢中的Restaurant對象?我不確定FindTheLatest在做什麼,但應該是_db.Reviews.Include(r => r.Restaurant).FindTheLatest(1).Single()或_db.Reviews.Include(「Restaurant」)。FindTheLatest(1 ).Single() – Khepri
@Khepri我是新來的實體框架。你能說說'包括'方法嗎? –
包含在結果中加載導航屬性。如果您不包含該語句,則不填充導航屬性的結果。 – Khepri