简体   繁体   中英

EF Core query stored procedure map to types

I have a project that needs to query a database and return results to web api. There are several stored procedures that are created on the fly by the DB Admin and they have a UI that they create the definition of the stored procedure and the name of it and the web api service just calls that SP and should return the result. Based on the below code I cannot get the return object to web api controller as object contains items but with no properties mapped.

var result = dbContext.Query<object>().AsNoTracking().FromSql(
            "dbo.MY_SP @DateFrom=@DateFrom, @DateTo=@DateTo",
            dateFromParam, dateToParam).ToList();

In your case, you need to use dynamic to represents the result of stored procedure.

Add the following method in your DbContext class:

public IEnumerable<dynamic> GetDynamicResult(string commandText, params SqlParameter[] parameters)
{
    // Get the connection from DbContext
    var connection = DbContext.Database.GetDbConnection();

    // Open the connection if isn't open
    if (connection.State != System.Data.ConnectionState.Open)
        connection.Open();

    using (var command = connection.CreateCommand())
    {
        command.CommandText = commandText;
        command.Connection = connection;

        if (parameters?.Length > 0)
        {
            foreach (var parameter in parameters)
            {
                command.Parameters.Add(parameter);
            }
        }

        using (var dataReader = command.ExecuteReader())
        {
            // List for column names
            var names = new List<string>();

            if (dataReader.HasRows)
            {
                // Add column names to list
                for (var i = 0; i < dataReader.VisibleFieldCount; i++)
                {
                    names.Add(dataReader.GetName(i));
                }

                while (dataReader.Read())
                {
                    // Create the dynamic result for each row
                    var result = new ExpandoObject() as IDictionary<string, object>;

                    foreach (var name in names)
                    {
                        // Add key-value pair
                        // key = column name
                        // value = column value
                        result.Add(name, dataReader[name]);
                    }

                    yield return result;
                }
            }
        }
    }
}

Now you can invoke your stored procedure in this way:

var result = dbContext.GetDynamicResult(" exec [dbo].[MySp] @dateFrom, @dateTo ", new SqlParameter("@dateFrom", dateFrom), new SqlParameter("@dateTo", dateTo));

Please let me know if this answer is useful.

Regards.

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