简体   繁体   English

使用EntityFramework中的ID列表更新条目列表

[英]Update a List of entries using a List of ID's in EntityFramework

I'm using the following code to store a list of connectionID's in a List<string> : 我正在使用以下代码在List<string>存储connectionID的List<string>

List<string> connectionIds =
                    connectedUsers.Where(x => x.UserId == userId).Select(x => x.ConnectionId).ToList();

I need to update the Database to set the connection status to false when it finds the corresponding ID's. 我需要更新数据库,以便在找到相应的ID时将连接状态设置为false So far, I am using the following code: 到目前为止,我使用以下代码:

if (connectionIds.Any())
                {
                    foreach (string connectionId in connectionIds)
                    {
                        Connection curConn = db.Connection.FirstOrDefault(x => x.ConnectionID == connectionId);
                        if (curConn != null)
                            curConn.Connected = false;
                        db.SaveChanges();
                    }
                }

However, this makes a call to the DB for each connection... Is there any simple way to update the connection in an easier process? 但是,这会为每个连接调用DB ...有没有简单的方法在更简单的过程中更新连接?

You can use the Contains method. 您可以使用Contains方法。 This will result in a single query for loading the connection objects. 这将导致单个查询以加载连接对象。 Once you have the result of the query, loop through the results to update the Connected flag, and then save the changes. 获得查询结果后,循环结果以更新Connected标志,然后保存更改。

List<string> connectionIds = ...;

if (connectionIds.Any()) {
    var data = db.Connection
        .Where(x => connectionIds.Contains(x.ConnectionID))
        .ToList();
    foreach (var item in data) {
        item.Connected = false;
    }
    db.SaveChanges();
}

You want to perform batch updates in one SQL statement with EF. 您希望使用EF在一个SQL语句中执行批量更新。 EF doesn't support this in a straightforward manner. EF不直接支持这一点。 See here for a possible solution. 请参阅此处了解可能的解决方案

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

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