【问题标题】:EF model with list of objects带有对象列表的 EF 模型
【发布时间】:2019-06-12 17:01:07
【问题描述】:

我将创建应用程序来保存健身结果。 我有课练习:

public class Exercise
{
    public Guid Id { get; protected set; }
    public string Name { get; protected set; }
    public Category Category { get; protected set; }
}

以及包含练习列表的培训计划:

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。但是我想为一些计划分配锻炼,这种情况的最佳解决方案是什么?

【问题讨论】:

标签: c# .net entity-framework asp.net-core


【解决方案1】:

谢谢帮助,我使用多对多。 解决了,我新建了一个类:

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

不幸的是,我又被卡住了。当我想使用这种方法从 DB 单记录 TrainingPlan 中获取时:

        public TrainingPlan Get(Guid id)
        => _context.TrainingPlans.Include(x => x.Exercises).Single(x => x.Id == id);

我在 List TrainingPlanExercise 中收到了带有 null 锻炼的记录。

我应该在 DbContext 中添加更多内容还是有其他解决方案?

顺便说一句。我使用的是 EF 核心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    相关资源
    最近更新 更多