简体   繁体   中英

Avoid entity duplication with Linq in ASP.NET Core Web API

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).

  1. You need to trim the name ( name.trim() ) for both names from entity and dto

  2. You need to remove all the whitespaces in between ( string.replace(" ", string.empty())

  3. You need to change everything to lower case ( string.lower() )

  4. 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.

  1. Introduce another column (This can be a primary key with other keys) and save the name with trimming and lowercase when you insert a new record to that table.

Example: Original Name: Amir Masoud Babaei --> New Column value: amirmasoudbabaei

  1. 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.

  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM