C#C
C#12mo ago
Zoli

✅ UNIQUE constraint failed

I have the following relationships
One workout can have multiple exercises and each exercise can have one exercise variant I would like to implement this but I am getting an exception when saving a newly created workout
An error occurred while saving the entity changes.See the inner exception for details.
// ---> Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'UNIQUE constraint failed: ExerciseVariant.Id'.


My classes
[Table(nameof(Workout))]
public class Workout
{
    [Key]
    public Guid Id { get; set; }

    // Other properties

    public ICollection<Exercise> Exercises { get; } = new List<Exercise>();
}


[Table(nameof(Exercise))]
public class Exercise
{
    [Key]
    public Guid Id { get; set; }

    // Relationship with ExerciseVariant
    public Guid ExerciseVariantId { get; set; }  // Foreign key
    public ExerciseVariant ExerciseVariant { get; set; } = null!;  // Navigation property

    // Relationship with Workout
    public Guid? WorkoutId { get; set; }
    public Workout? Workout { get; set; }

    // Other properties
}

[Table(nameof(ExerciseVariant))]
public class ExerciseVariant
{
    [Key]
    public Guid Id { get; set; }

    public ICollection<Exercise> Exercises { get; } = new List<Exercise>();

    // Other properties
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Configure relationships
    modelBuilder.Entity<Exercise>()
        .HasOne(e => e.ExerciseVariant)
        .WithMany(ev => ev.Exercises)
        .HasForeignKey(e => e.ExerciseVariantId);

    // Workouts
    modelBuilder.Entity<Workout>()
          .HasMany(o => o.Exercises)
          .WithOne(o => o.Workout)
          .HasForeignKey(o => o.WorkoutId)
          .OnDelete(DeleteBehavior.Cascade);

    base.OnModelCreating(modelBuilder);
}



ExerciseVariants is bulked inserted from an api when the app first launched.
Was this page helpful?