Is there a better way to do updates in LinqToSQL?
Posted
by Vaccano
on Stack Overflow
See other posts from Stack Overflow
or by Vaccano
Published on 2010-03-17T22:08:03Z
Indexed on
2010/03/17
22:11 UTC
Read the original article
Hit count: 190
I have a list (that comes to my middleware app from the client) that I need to put in my database. Some items in the list may already be in the db (just need an update). Others are new inserts.
This turns out to be much harder than I thought I would be. Here is my code to do that. I am hoping there is a better way:
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();
}
This seems like a lot of work to do a simple update. But maybe I am just spoiled.
Anyway, if there is a easier way to do this please let me know.
Note: If you are curious the code to the LambdaComparer is here: http://gist.github.com/335780#file_lambda_comparer.cs
© Stack Overflow or respective owner