c# - Entity Framework 空对象

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

我有一个名为 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 为空!而另一个属性具有值(value)。我的代码有什么问题?

最佳答案

要么通过Include 方法显式加载导航属性Restaurant:

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

或者您可以通过将其设为虚拟来为该属性启用延迟加载:

public virtual Restaurant Restaurant { get; set; }

您可以阅读更多有关加载相关实体的信息 here .

关于c# - Entity Framework 空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13523681/

相关文章:

java - 异常描述 : An incompatible mapping has been encountered between [class sws.Entity.Appointment] 和 [class sws.entities.User]

c# - 图像透明度与另一个向后 c#

c# - .NET Core - 有没有办法实现 WinForms?

asp.net-mvc - ASP.NET 身份和声明

javascript - Bootstrap Glyphicon(折叠和展开)不工作

entity-framework - Entity Framework 尝试选择不存在的列?

c# - 当 .NET 线程抛出异常时会发生什么?

c# - 使用正则表达式从 XML 字符串中删除 XML 节点命名空间前缀

jquery - SignalR 1.0.1 使用 Chrome 的跨域请求 (CORS)

c# - 更智能的 Entity Framework Codefirst 流畅的 API