有没有更好的方法在Linq To SQL中进行更新?

时间:2010-03-17 22:08:03

标签: c# linq linq-to-sql

我有一个列表(来自客户端的中间件应用程序),我需要将其放入我的数据库中。列表中的某些项可能已经在数据库中(只需要更新)。其他是新的插页。

事实证明这比我想象的要困难得多。这是我的代码。我希望有更好的方法:

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

2 个答案:

答案 0 :(得分:3)

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();
}

答案 1 :(得分:0)

不是更好的方式,而是替代方案:

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