【发布时间】: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的主键吗?