简体   繁体   中英

Executing Shrink on SQL Server database using command from linq-to-sql

I'm looking for a way to clear transaction logs; in particular, I want to shrink the logs. I know there are bad reasons for wanting to do it but in this instance, it's for a good reason.

I've run this in SQL Server Management:

DBCC SHRINKFILE(DBName_log)
DBCC SHRINKFILE(DBName)

That does what I need. Now I want to execute this command from code using Linq-To-SQL, something like this:

using (MyDC TheDC = new MyDC())
{
   TheDC.ExecuteCommand(....);
}

What command do I need to send to get both these actions executed in the database?

Your DbContext exposes a System.Data.Entity.Database offering a method ExecuteSqlCommand() that has a couple of overloads.

Here's the documentation from the MSDN article.

Executes the given DDL/DML command against the database. As with any API that accepts SQL it is important to parameterize any user input to protect against a SQL injection attack. You can include parameter place holders in the SQL query string and then supply parameter values as additional arguments. Any parameter values you supply will automatically be converted to a DbParameter.

According to your needs, I would use the following:

context.Database.ExecuteSqlCommand("DBCC SHRINKFILE(DBName_log)" ... ); 

The document also goes on to explain how to bind a parameter which, for performance, I strongly recommend you do whenever you're executing anonymous queries against SQL Server or Oracle.

Alternatively, you can also construct a DbParameter and supply it to SqlQuery. This allows you to use named parameters in the SQL query string.

Again, per your requirement:

context.Database.ExecuteSqlCommand(
    "DBCC SHRINKFILE(@file)", 
    new SqlParameter("@file", DBName_log)
);

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