I need help with getting the ID of a newly inserted record when running an SQL insert command through LINQ. I’m trying to insert data and then retrieve the auto-generated ID value, but my current approach isn’t working properly. Here’s what I’m attempting:
string sqlCommand = "insert into CompanyDivisions ";
sqlCommand += "(departmentID, Priority, companyReportID) ";
sqlCommand += "values(" + divisionData.departmentID + ", " + divisionData.Priority + ", " + divisionData.CompanyReport.ReportID + ") ";
sqlCommand += "select scope_identity()";
var insertedID = _dbContext.ExecuteQuery<int>(sqlCommand).ToList()[0];
Can someone point out what might be wrong with this syntax? I expected this to return the ID of the newly created record, but it’s not behaving as expected. Is there a better way to handle this scenario?