如何使用 C# Datastax 驱动程序在 Cassandra 上删除 table?

How to delete table on Cassandra using C# Datastax driver?

var keyspace = "mydb";
var datacentersReplicationFactors = new Dictionary<string, int>(0);
var replication = ReplicationStrategies.CreateNetworkTopologyStrategyReplicationProperty(datacentersReplicationFactors);

using (var cluster = Cluster.Builder().AddContactPoints("my_ip").Build())
using (var session = cluster.Connect())
{
    session.CreateKeyspaceIfNotExists(keyspace, replication, true);
    session.ChangeKeyspace(keyspace);

    var entityTable = new Table<Models.Entity>(session);
    var attributeTable = new Table<Models.Attribute>(session);

    entityTable.CreateIfNotExists(); // Worked
    attributeTable.CreateIfNotExists(); // Worked

    entityTable.Delete(); // Does nothing
    attributeTable.Delete();  // Does nothing
}

编辑: 不使用原始查询 session.Execute("DROP TABLE entities;"); 工作正常。

Delete() 方法不适用于删除 table。它 returns 表示一条 DELETE cql 语句。如果你调用它,你只会得到 {DELETE FROM entities}.

如果你需要删除一个table,最简单的方法就是执行DROP语句:

session.Execute("DROP TABLE entities;");

除非已经有我不知道的删除表的方法,否则您可以使用此扩展。

public static class DastaxTableExtensions
{
    public static void Drop<T>(this Table<T> table)
    {
        table.GetSession().Execute($"DROP TABLE {table.Name};");
    }

    public static void DropIfExists<T>(this Table<T> table)
    {
        table.GetSession().Execute($"DROP TABLE IF EXISTS {table.Name};");
    }
}

那你就可以这样使用了

entityTable.Drop();
attributeTable.DropIfExists();