Entity framework core 未从数据库加载引用的对象
这是我的表格结构:Entity framework core 未从数据库加载引用的对象,entity-framework-core,asp.net-core-2.0,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; } pub
#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
我收到了一个好的和旧的“对象引用未设置为对象的实例”。检查结果时,请查看WorkoutExchanges中的Exchanges属性为null
以下是使用代码优先方法创建数据库的方式:
所以,问题是:为什么练习不包括在练习对象中?我是否需要以某种方式包含它?我使用的是.NETCore2简单的答案是在EFCore中没有延迟加载。尚未发布,但如果您想涉猎alpha代码,请将其保存在存储库中。根据您的课程,在WorkoutExercise中没有练习的集合
然后您需要
thenclude(w=>w.Exercises)
遵循您的Include子句,因为EFCore不进行延迟加载。我找到了以下解决方案
更改我的代码如下:
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();
var-top=context
.Set()
.Where(q=>q.ProfileId==ProfileId&&q.User.UserId==UserId)
.包括(q=>q.练习)
.SingleOrDefault();
上下文
.入口(顶部)
.Collection(e=>e.WorkoutExercises)
.Query()
第()类
.包括(e=>e.练习)
.Load();
它成功了您好,我在实体模型的训练练习表上没有看到任何外键。您是否有更多关于DbContext.OnCreating的配置?此外,我发现您的声明中没有包含用户表。也许空引用毕竟是用户对象?嗨,谢谢你的回答。外键是由EF计算出来的,据我所知,不需要隐式指示(我也在数据库中看到)。事实上,在没有Include语句的情况下,用户被加载是没有问题的,我猜这是因为被查询的主要对象的子对象。嗨,谢谢你的回答。Exercise不假定为WorkoutExercises中的集合,而是一个导航属性。它更像是为了锻炼而扩展了锻炼表。从逻辑上讲,你有一个练习列表,你可以在你的锻炼计划中选择。更新的答案包括你的问题的可能解决方案。我在发布之前确实尝试过,EF说练习与WorkoutProfiles表没有关系,这是正确的,因为我认为您的类或上下文中的映射需要更多,因为您像EF6惰性加载那样编码属性,它在EFCORE中不起作用
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();