0

I am trying to read the size of my database, and I can do this in SQL Server - but how do I run the following code in Entity Framework and get the output?

USE Impro_V2
GO
sp_spaceused
GO

or

EXEC sp_helpdb N'Impro_V2';

Using context.Database.ExecuteSqlCommand I get a result of "-1". I am not even sure whether that is failed.

How do run code like that?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sonnich
  • 151
  • 2
  • 11
  • You can use the `context.Database.GetDbConnection` extension method to get the underlying `DbConnection` object, and then use it to execute raw ADO.NET commands. – Richard Deeming Feb 07 '22 at 16:45
  • Does this answer your question? [How to call Stored Procedure in Entity Framework 6 (Code-First)?](https://stackoverflow.com/questions/20901419/how-to-call-stored-procedure-in-entity-framework-6-code-first) – devlin carnate Feb 07 '22 at 16:45
  • For some reason I dont see the GetDbConnection. The other does not give much, just a "-1" – sonnich Feb 08 '22 at 09:24

1 Answers1

0

The answer is here: How to know the physical size of the database in Entity Framework?

The code is simple:

var ef = new MyDbContext();
var sqlConn = ef.Database.Connection as SqlConnection;

var cmd = new SqlCommand("sp_spaceused")
{
    CommandType = System.Data.CommandType.StoredProcedure,
    Connection = sqlConn as SqlConnection
};
var adp = new SqlDataAdapter(cmd);
var dataset = new DataSet();
sqlConn.Open();
adp.Fill(dataset);
sqlConn.Close();
// example read
foreach (DataTable table in dataset.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            console.write(row[icol].tostring());
etc
sonnich
  • 151
  • 2
  • 11