EF Core, after adding (INSERT) data to the OBD, immediately obtains (SELECT) ID from it. And in your handle code, I only see INSERT.You have to do that.public async Task<int> CreateDataAsync(FormAbsence model)
{
if (model == null)
return 0;
var sqlExpression =
"INSERT INTO FormAbsence (reason, start_date, duration, discounted, description) " +
"VALUES (@reason, @startDate, @duration, @discounted, @description); " +
"SELECT scope_identity();";
using (var connection = new SqlConnection(_context.ConnectString))
{
await connection.OpenAsync();
using (var command = new SqlCommand(sqlExpression, connection))
{
command.Parameters.Add("reason", SqlDbType.NVarChar).Value = model.Reason;
command.Parameters.Add("startDate", SqlDbType.DateTime2).Value = model.StartDate.Date;
command.Parameters.Add("duration", SqlDbType.Int).Value = model.Duration;
command.Parameters.Add("discounted", SqlDbType.NVarChar).Value = model.Discounted;
command.Parameters.Add("description", SqlDbType.NVarChar).Value = model.Description;
int id = (int)(decimal)(await command.ExecuteScalarAsync());
model.Id = id;
return id;
}
}
}
Make sure you use the parametered queries! This will completely eliminate sql injections and increase productivity.I don't know what type you have in the table, so edit yourself. SqlDbType♪Like, I'm not sure about the type coming back. id♪ Tell me the right thing.Your method is returning Task<int> - what does that mean? int? I got it back. idbut it doesn't make much sense. You decide.If the logic is included in EF Core, approximately such a request will be generated when the data are collected (Orders and UserId - the name of the table and columns in my OBD:SET NOCOUNT ON;
INSERT INTO [Orders] ([UserId])
VALUES (@p0);
SELECT [Id]
FROM [Orders]
WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();
As can be seen, immediately after the retrieval, a newly-gen. scope_identity() and this value is returning. And EF Core updates Id In fact.I'll tell you what. https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-ver15 - this is Sql Server. There's something else to be used in working with another SBS. ORM releases us from the code translating into another DSB (not always).Judging by SqlConnection♪ SqlCommand You work exactly with Sql Server.What? https://docs.microsoft.com/en-us/sql/t-sql/statements/set-nocount-transact-sql?view=sql-server-ver15 ♪ If you need it, think for yourself.