繁体   English   中英

EF Core - 在运行时删除模式中的数据库表

[英]EF Core - Delete database tables in a schema at runtime

我有一个ASP.NET Core Web API使用EF Core配置并使用SQL Server。 我有一个控制器,它在post上向数据库添加表,并且应该在删除时从数据库中删除这些表。 添加的表将添加到单独的模式中。

如何在运行时删除新创建的模式中的表?

这是生成表的代码:

RelationalDatabaseCreator databaseCreator = 
    (RelationalDatabaseCreator) context.Database.GetService<IDatabaseCreator>();
databaseCreator.CreateTables();

以及架构名称如何应用于上下文:

public DbSet<CustomEntity> CustomEntities { get;set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);
     modelBuilder.ApplyConfiguration(new EntityConfiguration<CustomEntity>(nameof(CustomEntities), schemaName));
}

EntityConfiguration类:

public class EntityConfiguration<T> : IEntityTypeConfiguration<T> where T : class
{
    private readonly string tableName;
    private readonly string schema;

    public EntityConfiguration(string tableName, string schema)
    {
        this.tableName = tableName;
        this.schema = schema;
    }

    public void Configure(EntityTypeBuilder<T> builder)
    {
        if (!string.IsNullOrEmpty(schema))
        {
            builder.ToTable(tableName, schema);
        }
    }
}

实体框架没有直接管理模式的功能,因为它是为数据级别的CRUD设计的。 您可以使用原始SQL命令来实现此目的,但是,就目前而言,EF Core无法开箱即用(它只能使用FromSql()序列化查询)。 如果您确定仍在EF Core中执行此操作,则此帖子可能有用: 在Entity Framework Core 2.0中执行SQL命令以删除表中的所有数据

USING [Database-Name]
EXEC sp_MSforeachtable 'DROP TABLE ?'
GO

您可能必须事先删除外键和其他约束。

暂无
暂无

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

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