我将创建应用程序以保存健身成绩。 我上课练习:
public class Exercise
{
public Guid Id { get; protected set; }
public string Name { get; protected set; }
public Category Category { get; protected set; }
}
和包含训练清单的TrainingPlan类:
public class TrainingPlan
{
public Guid Id { get; protected set; }
public string Name { get; protected set; }
public IEnumerable<Exercise> Exercises { get; protected set; }
}
我创建EntityFramework DbContext:
public class GymContext : DbContext
{
public GymContext(DbContextOptions<GymContext> options) : base(options) { }
public DbSet<Exercise> Exercises { get; set; }
public DbSet<TrainingPlan> TrainingPlans { get; set; }
}
然后我使用了命令add-migration和update-database。对于带有运动的表,EF已在TrainingPlanId中添加了其他字段。因此,现在我只能将受权人锻炼分配给一个TrainingPlan。但是我想为一些计划分配锻炼,对于这种情况最好的解决方案是什么?
答案 0 :(得分:0)
寻求帮助,我使用了很多很多。 解决了,我开设了新班级:
public class TrainingPlanExercise
{
public Guid TrainigPlanId { get; protected set; }
public TrainingPlan TrainigPlan { get; protected set; }
public Guid ExerciseId { get; protected set; }
public Exercise Exercise { get; protected set; }
}
然后在TrainingPlan中,我将“锻炼清单”替换为TrainingPlanExercise清单。
我的EntityFramework DbContext现在看起来是:
public class GymContext : DbContext
{
public GymContext(DbContextOptions<GymContext> options) : base(options) { }
public DbSet<Exercise> Exercises { get; set; }
public DbSet<TrainingPlan> TrainingPlans { get; set; }
public DbSet<TrainingPlanExercise> TrainingPlanExercises { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TrainingPlanExercise>()
.HasKey(e => new { e.ExerciseId, e.TrainigPlanId });
modelBuilder.Entity<TrainingPlanExercise>()
.HasOne(x => x.TrainigPlan)
.WithMany(x => x.Exercises)
.HasForeignKey(x => x.TrainigPlanId);
}
}
不幸的是,我再次陷入困境。当我想使用这种方法从数据库单条记录TrainingPlan中获取时:
public TrainingPlan Get(Guid id)
=> _context.TrainingPlans.Include(x => x.Exercises).Single(x => x.Id == id);
我在List TrainingPlanExercise中收到锻炼为空的记录。
我应该在DbContext中添加更多内容还是有其他解决方案?
顺便说一句。我使用EF核心。