【问题标题】:What is the best way to check if an item of a list already exists in database?检查数据库中是否已存在列表项的最佳方法是什么?
【发布时间】:2020-11-08 21:58:15
【问题描述】:

我有一个要插入数据库的人员对象的列表,但首先我需要知道列表中的每个人是否已经存在于数据库中。 (我没有使用任何像 EntityFramework 这样的 ORM, 只是 Oracle 提供商的 ADO.NET)

例如:

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
}

我需要知道这种方法是否是最好的方法,因为在这个例子中,我将为列表中的每个人打开/关闭连接,然后去查询数据库到一个可能有数百万的表记录。

或者我可以只调用一次数据库,然后将表中的数百万条记录分配给一个列表。

像这样:

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
 }

在这两个示例中,解决我遇到的这个问题的最佳方法是什么?或者如果您有其他解决方案,请告诉我。

【问题讨论】:

  • DocumentId是Person的主键吗?

标签: c# oracle linq ado.net


【解决方案1】:
var listOfPersons = new List<Person>();
var inputPersonIds = listOfPersons.Select(p => p.Id).ToList();

修改db.getPersonsInDb()方法以在准备sql命令时使用in关键字传递inputPersonIds

例如:

select * from person where id in inputPersonIds 

【讨论】:

    【解决方案2】:

    您可以在单个调用中检查是否存在记录(类似于where id in ()。并获取所有那些 id 或表中不存在条目的某些唯一键。然后将行插入表中。您可以也可以批量插入。

    【讨论】:

      猜你喜欢
      • 2010-10-01
      • 2012-06-17
      • 2016-08-16
      • 2012-08-29
      • 2011-05-25
      • 2015-01-10
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多