I want to know the best way of avoiding entity duplication in an ASP.NET Core Web API project.
Imagine that you have a product with a name and manufacturer and you want to make sure if the name is not duplicated. Imagine that a new product with a name came from client (dto) and we need to look if the name (entity) already exists in the database (using EF).
You need to trim the name ( name.trim()
) for both names from entity and dto
You need to remove all the whitespaces in between ( string.replace(" ", string.empty())
You need to change everything to lower case ( string.lower()
)
Finally you need to compare these two
Is there any best practices how to do this without writing all the code? I tried to use string.compare
with the compareoptions
like ignorecase
and ignoresymbols
and also the string.equal()
with ignorecase
option but the EF gives me an alarm that it can not translate the code.
br
I have a suggestion for your approach.
Example: Original Name: Amir Masoud Babaei --> New Column value: amirmasoudbabaei
And when you insert a new record, do your trimming and lowercase changes and save it to the database. Since it is a primary key, it should throw an error.
So with this approach, you don't need to loop through all the names and validate if the name is already exist.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.