I'm using the following code to store a list of connectionID's in a 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. 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?
You can use the Contains method. 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.
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 doesn't support this in a straightforward manner. See here for a possible solution.
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.