简体   繁体   English

使用来自 linq-to-sql 的命令在 SQL Server 数据库上执行收缩

[英]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:我在 SQL Server 管理中运行了这个:

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:现在我想使用 Linq-To-SQL 从代码中执行此命令,如下所示:

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.您的DbContext公开了一个System.Data.Entity.Database提供了一个方法ExecuteSqlCommand() ,该方法有几个重载。

Here's the documentation from the MSDN article.这是 MSDN 文章中的文档

Executes the given DDL/DML command against the database.对数据库执行给定的 DDL/DML 命令。 As with any API that accepts SQL it is important to parameterize any user input to protect against a SQL injection attack.与任何接受 SQL 的 API 一样,参数化任何用户输入以防止 SQL 注入攻击很重要。 You can include parameter place holders in the SQL query string and then supply parameter values as additional arguments.您可以在 SQL 查询字符串中包含参数占位符,然后提供参数值作为附加参数。 Any parameter values you supply will automatically be converted to a DbParameter.您提供的任何参数值都将自动转换为 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.该文档还继续解释如何绑定参数,为了提高性能,我强烈建议您在对 SQL Server 或 Oracle 执行匿名查询时这样做。

Alternatively, you can also construct a DbParameter and supply it to SqlQuery.或者,您也可以构造一个 DbParameter 并将其提供给 SqlQuery。 This allows you to use named parameters in the SQL query string.这允许您在 SQL 查询字符串中使用命名参数。

Again, per your requirement:再次,根据您的要求:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM