[英]What is the best way to check if an item of a list already exists in database?
我有一個要插入數據庫的人 object 的列表,但首先我需要知道列表中的每個人是否已經存在於數據庫中。 (我沒有使用任何 ORM 之類的 EntityFramework,只是 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
}
我需要知道這種方法是否是最好的方法,因為在這個例子中,我將為列表中的每個人打開/關閉連接,然后 go 將數據庫查詢到可能有數百萬條記錄的表。
或者我可以只調用一次數據庫,然后將表中的數百萬條記錄分配給一個列表。
像這樣:
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
}
在這兩個示例中,解決我遇到的這個問題的最佳方法是什么? 或者,如果您有其他解決方案,請告訴我。
您可以在單個調用中檢查記錄是否存在(類似於where id in ()
。並獲取所有那些 id 或表中不存在條目的某些唯一鍵。然后將行插入表中。您可以批量操作也插入。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.