我有一个列表(来自客户端的中间件应用程序),我需要把它放在我的数据库中。列表中的某些项目可能已经在数据库中(只需要更新)。其他是新的插入。有没有更好的方式在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