简体   繁体   中英

Linq query to execute stored procedure with return type as DataTable

I am trying to get result as DataTable from a stored procedure using a Linq query. Here is the code that I am trying to use:

_dbContext.Database.Sqlquery<DataTable>("dbo.uspGetOrdersDetails @orderID", orderParam);

but the result is empty

屏幕快照,返回类型为DataTable

If I keep as viewmodel, then I am able to get the data

在此处输入图片说明

Just want to know that, is it possible with datatable.

EntityFramework or LinqToSql doesn't support this out of the box. Instead, you can use the connection of your context and fill your DataTable using Ado.Net. You can find a sample here . You can convert the solution provided in that answer to an extension method. A simple implementation:

public static class QueryExtensions
{
    public static DataTable ExecuteQuery(this DbContext db, string commandText, CommandType commandType, IEnumerable<SqlParameter> parameters)
    {
        var conn = db.Database.Connection;
        try
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            using (var command = conn.CreateCommand())
            {
                command.CommandText = commandText;
                command.CommandType = commandType;
                command.Parameters.AddRange(parameters.ToArray());
                using (var reader = command.ExecuteReader())
                {
                    var dt = new DataTable();
                    dt.Load(reader);
                    return dt;
                }
            }
        }
        finally
        {
            if (conn.State != ConnectionState.Closed) 
                conn.Close();
        }
    }
}

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