未从数据库

时间:2018-02-24 19:29:45

标签: entity-framework-core asp.net-core-2.0

这是我的表结构:

#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

在存储库类中,我运行以下linq查询:

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

我收到了旧的“对象引用未设置为对象的实例”。检查结果时,请参阅WorkoutExercises中的Exercises属性为空。

这是使用代码优先方法创建数据库的方式:

enter image description here

所以,问题是:为什么练习不包含在WorkoutExercises对象中?我需要以某种方式包含它吗?我正在使用.NET Core 2

2 个答案:

答案 0 :(得分:1)

简单的答案是EFCore中没有延迟加载。尚未发布,但如果您想涉及alpha代码,请将其存储在存储库中。根据您的课程,WorkoutExcercise中没有练习集合。

然后你需要ThenInclude(w => w.Exercises)跟随你的Include子句,因为EFCore不会进行延迟加载。

答案 1 :(得分:0)

我在this post

之后找到了一个解决方案

将我的代码改为:

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

它有效