简体   繁体   中英

Run entity framework core raw SQL without entity

I have this mysql stored-procedure:

CREATE DEFINER=`admin`@`%` PROCEDURE `Counter_increment2`(IN _Id VARCHAR(80), IN _CounterType VARCHAR(10), IN IncrBy INT)
BEGIN
    UPDATE Counter SET Value = @counter := Value + IncrBy WHERE Id=_Id AND CounterType=_CounterType;
    SELECT @counter as Value;
END

The result is: 在此处输入图像描述

I want to read the first cell in the first row into C# variable via EF.

I know that in the past EF provided SqlQuery<type> method for this kind of use.

How to do it right?

I think this is basically a repeat of the question answered here:

Get output parameter value of a stored procedure using EF Core?

Using the top answer in there helped me, though I admit that was EF Core 2.something. Might need tweaking for 3.x, assuming that's what you're using.

Note: for the specific case you've listed here (returning a single int column on a single row), I created my own extension method something like this:

public static class RDFacadeExtensions
{
    public static async Task<int> ExecuteScalarQueryAsync(this DatabaseFacade databaseFacade, string sql, params object[] parameters)
    {
        var concurrencyDetector = databaseFacade
            .GetService<IConcurrencyDetector>();

        using (concurrencyDetector.EnterCriticalSection())
        {
            var rawSqlCommand = databaseFacade
                .GetService<IRawSqlCommandBuilder>()
                .Build(sql, parameters);
            var result = await rawSqlCommand
                .RelationalCommand
                .ExecuteScalarAsync(
                    databaseFacade.GetService<IRelationalConnection>(),
                    parameterValues: rawSqlCommand.ParameterValues);

            return (int)result;
        }
    }
}

You should then be able to simply call:

int result = Context.Database.ExecuteScalarQueryAsync("exec procedure...");

To use...

(caveat: untested in this form, have been hiding at home for a while so a bit rusty too)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM