Search code examples
postgresqlentity-framework-6npgsql

postgreSQL returning Id's of updated rows using entity framework


I am trying to return the ID's of the rows that were affected by an update. I am using entity frameworks ExecuteSqlCommand and postgreSQL database. When I execute the command all I get as a return value is -1. What am I doing wrong?

var updatedIds = _dbContext.Database.ExecuteSqlCommand(@"UPDATE dbo.""PrincipleCategoryObjectives"" SET ""IsRequired""=" + requiredDto.IsRequired + @" WHERE ""AuditPrincipleId""=" + requiredDto.PrincipleId + @" RETURNING ""Id""");

Solution

  • ExecuteSqlCommand returns the number of rows affected, and not any value returned by the query itself (see the API docs).

    To get a value returned from your SQL, you can drop down to ADO.NET. Call _dbContext.Database.GetDbConnection() to get a plain old DbConnection, create a DbCommand on that connection with your SQL and call ExecuteScalar() on that (see the many tutorials on the web if you need help).