简体   繁体   中英

Is there a better way to do updates in LinqToSQL?

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

public void ProcessClients(List<Client> tempClients)
{
    foreach (Client client in tempClients)
    {
        Client originalClient = ctx.Clients.Where(a => a.Id == client.Id).SingleOrDefault();

        if (originalClient != null)
        {
            originalClient.ArrivalTime = client.ArrivalTime;
            originalClient.ClientId = client.ClientId;
            originalClient.ClientName = client.ClientName;
            originalClient.ClientEventTime = client.ClientEventTime;
            originalClient.EmployeeCount = client.EmployeeCount;
            originalClient.ManagerId = client.ManagerId;
        }
        else
        {
            ctx.Clients.InsertOnSubmit(client);
        }
    }

    ctx.SubmitChanges();
}

not a better way but an alternative:

ctx.AddtoClients(notInDB);
ctx.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM