Returning a DataTable using Entity Framework ExecuteStoreQuery

前端 未结 8 1414
清酒与你
清酒与你 2020-12-09 04:28

I am working with a system that has many stored procedures that need to be displayed. Creating entities for each of my objects is not practical.

Is it possible and

8条回答
  •  悲&欢浪女
    2020-12-09 05:13

    By the rule, you shouldn't use a DataSet inside a EF application. But, if you really need to (for instance, to feed a report), that solution should work (it's EF 6 code):

        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;
        }
    

提交回复
热议问题