我有一個列表(來自客戶端的中間件應用程序),我需要把它放在我的數據庫中。列表中的某些項目可能已經在數據庫中(只需要更新)。其他是新的插入。有沒有更好的方式在LinqToSQL中進行更新?
事實證明,這比我想象的要困難得多。這是我的代碼來做到這一點。我希望有更好的辦法:
public void InsertClients(List<Client> clients)
{
var comparer = new LambdaComparer<Client>((x, y) => x.Id == y.Id);
// Get a listing of all the ones we will be updating
var alreadyInDB = ctx.Clients
.Where(client => clients.Contains(client, comparer));
// Update the changes for those already in the db
foreach (Client clientDB in alreadyInDB)
{
var clientDBClosure = clientDB;
Client clientParam = clients.Find(x => x.Id == clientDBClosure.Id);
clientDB.ArrivalTime = clientParam.ArrivalTime;
clientDB.ClientId = clientParam.ClientId;
clientDB.ClientName = clientParam.ClientName;
clientDB.ClientEventTime = clientParam.ClientEventTime;
clientDB.EmployeeCount = clientParam.EmployeeCount;
clientDB.ManagerId = clientParam.ManagerId;
}
// Get a list of all clients that are not in my the database.
var notInDB = clients.Where(x => alreadyInDB.Contains(x, comparer) == false);
ctx.Clients.InsertAllOnSubmit(notInDB);
ctx.SubmitChanges();
}
這似乎很多工作做一個簡單的更新。但也許我只是被寵壞了。
無論如何,如果有更簡單的方法來做到這一點,請讓我知道。
注意:如果你是好奇的代碼到LambdaComparer是在這裏:http://gist.github.com/335780#file_lambda_comparer.cs