【问题标题】:EF Core - Delete database tables in a schema at runtimeEF Core - 在运行时删除架构中的数据库表
【发布时间】:2019-10-25 15:54:06
【问题描述】:

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

如何在运行时删除新创建的架构中的表?

这是生成表格的代码:

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);
        }
    }
}

【问题讨论】:

    标签: c# sql-server asp.net-web-api asp.net-core entity-framework-core


    【解决方案1】:

    实体框架没有直接管理模式的功能,因为它是为数据级别的 CRUD 设计的。您可以使用原始 SQL 命令来实现这一点,但是,到目前为止,EF Core 还没有开箱即用的能力(它只能使用FromSql() 序列化查询)。如果您确定仍要在 EF Core 中执行此操作,那么这篇文章可能会有用:Execute SQL command in Entity Framework Core 2.0 to delete all data in a table

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-28
      • 2017-04-23
      • 1970-01-01
      • 2020-01-25
      • 2021-12-02
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      相关资源
      最近更新 更多