简体   繁体   English

有没有更好的方法可以在LinqToSQL中进行更新?

[英]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 注意:如果您对LambdaComparer的代码感到好奇,请访问以下网址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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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