Returning datatable using entity framework

后端 未结 5 1524
南方客
南方客 2020-12-09 10:37

I am using entity framework. There is one particular situation in my application where I have to use a stored procedure. Since there are a lot of SQL statements written in t

5条回答
  •  孤街浪徒
    2020-12-09 11:10

    Just improving the previous solution, now including generic parameters (not SQL Server specific) and mutiple resultsets support:

        DataSet GetDataSet(string sql, CommandType commandType, Dictionary parameters)
        {
            // creates resulting dataset
            var result = new DataSet();
    
            // creates a data access context (DbContext descendant)
            using (var context = new MyDbContext())
            {
                // creates a Command 
                var cmd = context.Database.Connection.CreateCommand();
                cmd.CommandType = commandType;
                cmd.CommandText = sql;
    
                // adds all parameters
                foreach (var pr in parameters)
                {
                    var p = cmd.CreateParameter();
                    p.ParameterName = pr.Key;
                    p.Value = pr.Value;
                    cmd.Parameters.Add(p);
                }
    
                try
                {
                    // executes
                    context.Database.Connection.Open();
                    var reader = cmd.ExecuteReader();
    
                    // loop through all resultsets (considering that it's possible to have more than one)
                    do
                    {
                        // loads the DataTable (schema will be fetch automatically)
                        var tb = new DataTable();
                        tb.Load(reader);
                        result.Tables.Add(tb);
    
                    } while (!reader.IsClosed);
                }
                finally
                {
                    // closes the connection
                    context.Database.Connection.Close();
                }
            }
    
            // returns the DataSet
            return result;
        }
    

提交回复
热议问题