简体   繁体   English

实体框架核心中的截断表

[英]Truncate table in entity framework core

How can I truncate a certain table with C# code, not SQL query?如何使用 C# 代码截断某个表,而不是 SQL 查询?

I want the equivalent of TRUNCATE TABLE <table_name>我想要相当于TRUNCATE TABLE <table_name>

So far I've tried this:到目前为止,我已经尝试过:

context.Products.RemoveRange(context.Products);

however, it doesnt do anything但是,它什么也没做

You can't, that's not what an ORM is for.你不能,这不是 ORM 的用途。

An ORM helps you access the database in terms of object access. ORM 可帮助您在 object 访问方面访问数据库。 Truncating a table is a data layer operation, not an object operation.截断表是数据层操作,而不是 object 操作。 The equivalent in Entity Framework would be to load all objects from the database and delete them one by one. Entity Framework 中的等价物是从数据库中加载所有对象并一一删除。

You don't want that, you want to truncate the table.你不想要那个,你想截断表格。 Then dive down into SQL and truncate that table.然后深入到 SQL 并截断该表。

Surely there are extensions on Entity Framework that allow things like this, but in the end they will generate exactly the SQL you're preventing to execute, so why not simply do that yourself?当然,实体框架上有扩展允许这样的事情,但最终它们会生成你阻止执行的 SQL,那么为什么不简单地自己做呢?

re: extensions as mentioned by CodeCaster: If you are allowed to use NUGET packages in your code, you might find this library useful;回复:CodeCaster 提到的扩展:如果允许您在代码中使用 NUGET 包,您可能会发现这个库很有用; it has 'Truncate' and 'TruncateAsync' exactly as you've asked about.它完全按照您的要求具有“Truncate”和“TruncateAsync”。

https://github.com/borisdj/EFCore.BulkExtensions https://github.com/borisdj/EFCore.BulkExtensions

Yes, behind the scenes it is still using 'ExecuteSqlRaw', but using a c# method allows better error handling.是的,在幕后它仍在使用“ExecuteSqlRaw”,但使用 c# 方法可以更好地处理错误。 For example, in some cases database security may not allow table truncation by the executing thread, so if that's important to your application you can handle it easier with a wrapper.例如,在某些情况下,数据库安全性可能不允许执行线程截断表,因此如果这对您的应用程序很重要,您可以使用包装器更轻松地处理它。

I have done things as below, for EF Core 5.0.11 This is working for SQL Server, Oracle, PostgreSQL对于 EF Core 5.0.11,我已经完成了以下操作,这适用于 SQL 服务器、Oracle、PostgreSQL

public class AnnotationHelper
{
    /*
     * https://stackoverflow.com/questions/45667126/how-to-get-table-name-of-mapped-entity-in-entity-framework-core
     */
    private static string GetName(IEntityType entityType, string defaultSchemaName = "dbo")
    {
        //var schemaName = entityType.GetSchema();
        //var tableName = entityType.GetTableName();
        var schema = entityType.FindAnnotation("Relational:Schema").Value;
        string tableName = entityType.GetAnnotation("Relational:TableName").Value.ToString();
        string schemaName = schema == null ? defaultSchemaName : schema.ToString();
        string name = string.Format("[{0}].[{1}]", schemaName, tableName);
        return name;

    }

    public static string TableName<T>(DbSet<T> dbSet) where T : class
    {
        var entityType = dbSet.EntityType;
        return GetName(entityType);
    }
}
 

public static class EfHelper
{
    /*
     * need to install Microsoft.EntityFrameworkCore.Relational
     */
    public static string Truncate<T>(this DbSet<T> dbSet) where T : class
    {
        var context = dbSet.GetService<ICurrentDbContext>().Context;
        string cmd = $"TRUNCATE TABLE {AnnotationHelper.TableName(dbSet)}";        
        using (var command = context.Database.GetDbConnection().CreateCommand())
        {
            if (command.Connection.State != ConnectionState.Open)
            {
                command.Connection.Open();
            }
            command.CommandText = cmd;
            command.ExecuteNonQuery();
        }
        return cmd;
    }
}


[Test]
public void Truncate()
{
    Db.Users.Add(new User() 
    {
        Name = "Name",
        Email = "Email",
        CreatedBy = "CreatedBy",
        CreatedOn = DateTime.Now
    });
    Db.SaveChanges();
    Assert.GreaterOrEqual(Db.Users.ToList().Count, 1);

    /*Truncate table*/
    Db.Users.Truncate();
    Assert.AreEqual(0, Db.Users.ToList().Count);
}

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

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