✅ 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 ExerciseVariants is bulked inserted from an api when the app first launched.
15 Replies
When I want to create a workout:
I am getting an exception as
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'.What am I doing worng? Since
ExerciseVariant
is read only kind of metadata do I need to add ?
public ICollection<Exercise> Exercises { get; } = new List<Exercise>();
try removing
ExerciseVariantId = first.Id
, you already connect them on the line aboveStill the same.
check what
await _dbContext.ExerciseVariant.FirstOrDefaultAsync()
returns, i got same error if it was null
after putting something in the table, the example worked fineI am getting a valid ExerciseVariant.
are you reusing the same DbContext?
I think yes I do. I have a UoW wrapper around dbcontext
the context is already a unit of work
Yes I know just wanted to extend with some custom methods and etc.
Is using the same DbContext should be avoided?
yes, it should be short lived
you can use
.AddDbContextFactory
and inject that to construct context instancesSo in this case i register only UnitOfWork in the Di so means all repository gets the same DbContext. How is it possible to inject new for each repository?
don't forget to dispose of them. or use service scopes
Implementing the infrastructure persistence layer with Entity Frame...
.NET Microservices Architecture for Containerized .NET Applications | Explore the implementation details for the infrastructure persistence layer, using Entity Framework Core.
Ohhh looks good thanks a lot 🍻
Probably it will solve my issue. One more question if you dont mind. I have the ExerciseVariant table which is kind of metadata so only read only.
Do I need this list of exercise at all?
Each exercise can have one exercise variant, and exercise variant can be used for multiple exercise
they are all optional and for convenience. you can always tell ef core about entity relationships in OnModelCreating instead
sometimes you want to find all related entities and then a collection is useful instead of creating the query yourself
if the model changes to for example using a composite primary key, a navigation property would continue to generate the correct query, while a manual query would need to be updated