eddyuk
eddyuk

Reputation: 4190

Referenced object is not loaded from database

This the table structure I have:

#region Tables
public class WorkoutProfile
{
    public WorkoutProfile()
    {
        WorkoutExercises = new List<WorkoutExercise>();
    }
    [Key]
    public int ProfileId { get; set; }
    public string Name { get; set; }
    public int Sets { get; set; }
    public int RestAfterSetInSeconds { get; set; }
    public virtual User User { get; set; }
    public virtual ICollection<WorkoutExercise> WorkoutExercises { get; set; }
}

public class WorkoutExercise
{
    [Key]
    public int WorkoutId { get; set; }
    public virtual Exercise Exercise { get; set; }
    public int Order { get; set; }
    public int WorkoutTimeInSeconds { get; set; }
    public int RestAfterInSeconds { get; set; }
}

public class Exercise
{
    [Key]
    public long ExerciseId { get; set; }
    public string Title { get; set; }
    public string Visualisation { get; set; }
    public bool IsDefault { get; set; } // Is exersice should be included when user first registers
}

public class User
{
    [Key]
    public long UserId { get; set; }
    public string Email { get; set; }
    public DateTime Registered { get; set; }
}
#endregion Tables

In the repository class I run the following linq query:

return context
            .WorkoutProfiles.Include(w => w.WorkoutExercises)
            .Where(q => q.User.UserId == userId && q.ProfileId == profileId)
            .FirstOrDefault();

and I receive the good and old "Object reference not set to an instance of an object". When examining the result, see that Exercises property in WorkoutExercises is null.

This is how the database is created using code first approach:

enter image description here

So, the question is: why Exercises not included in WorkoutExercises object? Do I need to include it somehow? I am using .NET Core 2

Upvotes: 0

Views: 1276

Answers (2)

eddyuk
eddyuk

Reputation: 4190

I found a solution following this post

Altered my code as following:

var top = context
            .Set<WorkoutProfile>()
            .Where(q => q.ProfileId == profileId && q.User.UserId == userId)
            .Include(q => q.WorkoutExercises)
            .SingleOrDefault();

        context
            .Entry(top)
            .Collection(e => e.WorkoutExercises)
            .Query()
            .OfType<WorkoutExercise>()
            .Include(e => e.Exercise)
            .Load();

And it worked

Upvotes: 0

mvermef
mvermef

Reputation: 3914

The simple answer would be no lazy loading in EFCore. Not Released yet but if you want to dabble with alpha code, its in the repository. Based on your classes there are no collections for exercises in WorkoutExcercise.

Then you need to ThenInclude(w => w.Exercises) following your Include clause since EFCore doesn't do lazy loading.

Upvotes: 1

Related Questions