Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework null object

I have simple DBcontext class called OdeToFoodDb:

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);
    }
}

and the class definition:

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);
        }
    }
}

my problem is when i select a review from dbcontext like this:

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

I checked that the review.Restaurant is null! while the other property have a value. What is wrong with my code?

like image 245
Seyed Morteza Mousavi Avatar asked Nov 23 '12 05:11

Seyed Morteza Mousavi


People also ask

How do you handle a null object in C#?

IsNullOrEmpty() Method of C# If any string is not assigned any value, then it will have Null value. The symbol of assigning Null value is “ “or String. Empty(A constant for empty strings). This method will take a parameter that will be of System.

What is nullable object must have a value?

The value coming from the database is a nullable boolean. When you call Nullable. Value, and the value is null, you will get this exception.

How do I set the default value in entity Framework?

In the DbContext OnModelCreating you add the default value. The 'bool' property 'Active' on entity type 'Foundation' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type.


1 Answers

Either load navigation property Restaurant explicitly via Include method:

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

or you can enable lazy loading for that property, by making it virtual:

public virtual Restaurant Restaurant { get; set; }

You can read more about loading related entities here.

like image 76
Dennis Avatar answered Sep 30 '22 13:09

Dennis