Problems Executing Stored Procedure with Entity Framework

Kmcnet 1,006 Reputation points
2023-02-10T00:14:33.0666667+00:00

Hello everyone and thanks for the help in advance. Developing an application the executes a stored procedure from MVC page. The sproc simply reduces the available inventory of an item by 1 and increases the number used by 1. I have tested the sproc separately and it works fine. However, when I execute from EF, it fails. Here is the code:


            using (var ctx = new mDbContext())
            {
                var increment = ctx.tbl_Log_Inventory.FromSqlRaw("Exec sp_CountsByInventoryID @InventoryID", new SqlParameter("@InventoryID", 123456));
            }

Seems very simple, but doesn't work. Any help would be appreciated.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
779 questions
{count} votes

Accepted answer
  1. Jack J Jun 24,881 Reputation points Microsoft External Staff
    2023-02-10T07:39:42.3533333+00:00

    @Kmcnet, Welcome to Microsoft Q&A, if you want to update the database through the stored procedure, I recommend that you could use the context.Database.ExecuteSqlRaw Method instead of FromSqlRaw method. As usual, FromSqlRaw method is used to create a LINQ query based on a raw SQL query, which is also used to query data.

    Here is my code example and you could have a look.

    Stored Procedure:

    CREATE PROCEDURE [dbo].[TestProcedure]
    	@Name nvarchar(20)
    AS
    	Update products set Description='This is a test' where Name=@Name
    RETURN 0
    
    

    c# code:

                MyContext context = new MyContext();
                context.Database.ExecuteSqlRaw("TestProcedure @p0", parameters: new[] { "test1"});
    
    

    Tested result:

    User's image

    Hope my solution could help you.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.