Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I would like to update a record based on Id parameter, I have tried following step but that does not seem correct way to do because it generates compilation error:
public async Task CustomerUpdateAsync(string customerId)
await using var sqlConnection = new SqlConnection(_connectionString);
var sqlQuery = "UPDATE Customer(CustomerId,Name,Address,PostalCode,City)" +
"SET (@CustomerId,@Name,@Address,@PostalCode,@City)" +
$"WHERE CustomerId=@CustomerId", new {CustomerId = customerId};
await sqlConnection.ExecuteAsync(sqlQuery, customerId);
Error:
only assignment call increment decrement await and new object expressions can be used as a statement
–
await sqlConnection.ExecuteAsync(@"
UPDATE Customer
SET Name = @name, Address = @address,
PostalCode = @postalCode, City = @city
WHERE CustomerId=@customerId",
new { customerId, name, address, postalCode, city });
However, I don't know where you intend to get name, address, etc from - they aren't shown in the question.
Thanks guys I got it resolved by tweaking little :-
public async Task CustomerUpdateAsync(Customer customer)
await using var sqlConnection = new SqlConnection(_connectionString);
var sql = "UPDATE Customer SET Name=@Name,Address=@Address, PostalCode=@PostalCode," +
"City=@City WHERE CustomerId=@CustomerId";
await sqlConnection.ExecuteAsync(sql, new
CustomerId = customer.CustomerId,
Name = customer.Name,
Address = customer.Address,
PostalCode = customer.PostalCode,
City = customer.City
I am giving an example of single value update operation based on Id filed. Your may try as your own. I used SqlDataAdapter and SqlCommand class for this operation.
using (SqlConnection con = new SqlConnection(_connectionString))
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand sc = new SqlCommand("UPDATE [dbo].[TableName] SET [ColumnName] = @ValueToBeUpdated WHERE [Id] = @IdField", con);
sc.Parameters.AddWithValue("@ValueToBeUpdated", valueToBeUpdated);
adapter.UpdateCommand = sc;
con.Open();
adapter.UpdateCommand.ExecuteNonQuery();
catch (Exception ex)
logger.LogError($"Update failed! {ex.Message}");
throw ex;
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.