Cannot run stored procedure from Entity Framework Core

c# ef-core-2.0 entity-framework-core stored-procedures

Question

I have the following code in EF Core to run a stored procedure:

TenandId = user.TenantId;
userName = user.UserName;
updateDate = DateTime.Now;
TimeStart = 139601;
TimeEnd = 139612;
RequestId = id;

_context.TempRequest.FromSql("EXEC dbo.AddRequest_To_TempRequest @TimeStart, @TimeEnd, @TenantId, @UpdateDate, @UserName, @RequestId",
                new SqlParameter("@TimeStart", TimeStart),
                new SqlParameter("@TimeEnd", TimeEnd),
                new SqlParameter("@TenantId", TenandId),
                new SqlParameter("@UpdateDate", updateDate),
                new SqlParameter("@UserName", userName),
                new SqlParameter("@RequestId", RequestId));

but when I run it, it is not working, but it is also not throwing any errors.

Am I making any mistake?

Thank you

1
1
11/10/2019 11:34:24 AM

Popular Answer

FromSql is used when the raw SQL represents a query. And the method creates LINQ / EF Core query, but as usual with IQueryable<> / IEnumerable<> does not execute it until it is iterated (with foreach, ToList() etc.) - the so called deferred execution. This should explain why "it is not working, but it is also not throwing any errors".

For non query raw SQL statements EF Core provides another method ExecuteSqlCommand (or ExecuteSqlRaw / ExecuteSqlInterpolated in EF Core 3.0+) which executes immediately.

Both methods can be used to call stored procedure when executed. Looks like the later is more appropriate for your scenario, so replacing the

_context.TempRequest.FromSql

with

_context.Database.ExecuteSqlCommand

should do the job.

0
11/10/2019 11:34:02 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow