简体   繁体   English

在 ASP.NET 核心 Web ZDB974238714CA8DE634A7CE1DZ08A 中避免与 Linq 的实体重复

[英]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.我想知道在 ASP.NET 核心 Web API 项目中避免实体重复的最佳方法。

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).想象一下,一个带有名称的新产品来自客户端(dto),我们需要查看该名称(实体)是否已经存在于数据库中(使用 EF)。

  1. You need to trim the name ( name.trim() ) for both names from entity and dto您需要为 entity 和 dto 中的名称修剪名称( name.trim()

  2. You need to remove all the whitespaces in between ( string.replace(" ", string.empty())您需要删除之间的所有空格( string.replace(" ", string.empty())

  3. You need to change everything to lower case ( string.lower() )您需要将所有内容更改为小写( 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.我尝试将string.compareignorecasecompareoptionsignoresymbols选项以及带有ignorecase选项的string.equal()一起使用,但 EF 给了我一个警报,它无法翻译代码。

br 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示例:原始名称:Amir Masoud Babaei --> 新列值: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.因此,使用这种方法,您无需遍历所有名称并验证该名称是否已存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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