简体   繁体   English

检查数据库中是否已存在列表项的最佳方法是什么?

[英]What is the best way to check if an item of a list already exists in database?

I have a list of a person object that i want to insert in the database, but first i need to know if every person of the list already exists in the database or not.我有一个要插入数据库的人 object 的列表,但首先我需要知道列表中的每个人是否已经存在于数据库中。 (I'm not using any ORM like EntityFramework, just ADO.NET of Oracle provider) (我没有使用任何 ORM 之类的 EntityFramework,只是 Oracle 提供商的 ADO.NET)

For example:例如:

var listOfPersons = new List<Person>(); //this list could have 100 of person objects
     
//I need to check if every person of a list already exists in the database
foreach(var person in listOfPersons)
{
   //Here we made the call to the database for every person.
   //We make the query in the database to a table that could have millions of records        
   var existInDb = db.ExistPersonInDb(person.DocumentId); 

   //If not exists insert in the database
}

I need to know if this approach is the best way or not, because in this example i'll open/close the connection for every person in the list and then go to query the database to a table that could have a millions of records.我需要知道这种方法是否是最好的方法,因为在这个例子中,我将为列表中的每个人打开/关闭连接,然后 go 将数据库查询到可能有数百万条记录的表。

Or i could call the database just once and bring the millions of records of the table and assign it to a list.或者我可以只调用一次数据库,然后将表中的数百万条记录分配给一个列表。

Like this:像这样:

var personsInDb = db.getPersonsInDb().ToList(); //Get all the persons from database and add it to a list

var listOfPersons = new List<Person>(); //this list could have 100 of person objects

//I need to check if every person of a list already exists in the database
 foreach(var person in listOfPersons)
 {  
    //And here with Linq just check if the person that i want to insert already exists in the personsInDb list     
    var existInDb = personsInDb.Exists(p => p.DocumentId== person.DocumentId); 

    //If not exists insert in the database
 }

Of this two example what is the best way to solve this problem that i have?在这两个示例中,解决我遇到的这个问题的最佳方法是什么? Or if you have another solution please let me know.或者,如果您有其他解决方案,请告诉我。

You can check for existence of records in a single call ( similar like where id in () . And get all those id or some unique key for which no entry present in the table. And then insert rows into the table. You can do bulk insert also.您可以在单个调用中检查记录是否存在(类似于where id in () 。并获取所有那些 id 或表中不存在条目的某些唯一键。然后将行插入表中。您可以批量操作也插入。

var listOfPersons = new List<Person>();
var inputPersonIds = listOfPersons.Select(p => p.Id).ToList();

Modify db.getPersonsInDb() method to pass the inputPersonIds using the in keyword while preparing the sql command.修改db.getPersonsInDb()方法以在准备 sql 命令时使用 in 关键字传递inputPersonIds

For eg:例如:

select * from person where id in inputPersonIds 

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

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