❔ EFCore: Unique Category Name
I have an issue with the entity "Category" that I have.
Each "Target" Entity can have several categories, each category has a name and an Id.
Target Entity has a List of Categories, however now when trying to add categories to an Entity there are duplicates.
If I have two entities and add a category with the same name to both, there will be a dupe category (as the name exists two times and the name of Category entity should be unique)
19 Replies
so I aim for this structure, what is the easiest way to achieve it with efcore?
the two models
Just configure a unique index on the
Category.Name
property, either with (bad)annotations or (good) IEntityConfigurationoh damn that rlly all?
haha
well, yes?
didnt think of it
but yeah makes sense
it wont automagically work when inserting a new
Target
thou, just fyiso now if I add category to Target A and B with same name it does map it via the ID of the category and not create dupe?
yes, assuming tracked entities
ok will check
this will fail because A already exists
it wont look up the category and map it, you'd have to do that yourself, but that would be the same if not using EF
it doesnt rlly fail it just updates the referenced ID. The structure is not correct in the DB, not as I wanted it to be. How can I tell it that one category is not bound to one ScrapeTarget? but that multiple targets can have the same category so it uses my mapping that I wished
this is category table
Ah right, since you dont have a reverse nav property it doesnt assume many to many
so either add the reverse nav property, or manually configure the relationship in your
IEntityConfiguration
ok I fixed that.
Now there is the issue that I cannot add two targets with same category due to unique constraint. I assume because it is trying to add the category again but it cannot. Not sure whats best solution for this
this would throw
no, that should work fine
you also dont need to use
await AddAync
just use Add
you are not using HiLo I assumeyou are right, my bad.
it works like this
is there any limitation i need to consider?
I guess two instances with same name would not work for category
then it would throw probably
but thats ok
correct
Alright thanks for the help, new to efcore so kinda still nooby but once learned its a lot more efficient to code, no need for nasty sql queries anymore
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.