Pomelo.entityframeworkcore.mysql: Como obter todos os nomes de tabela com Pomelo.EntityFrameworkCore.MySql?

Criado em 24 dez. 2020  ·  4Comentários  ·  Fonte: PomeloFoundation/Pomelo.EntityFrameworkCore.MySql

Quero verificar se existe alguma tabela, então como obter todos os nomes de tabelas?

usar CreateCommand () para fazer uma consulta personalizada?

closed-question type-question

Comentários muito úteis

Uh oh, talvez eu não possa, eu tenho um limite de perguntas no Stack Overflow. - Muita pergunta pessoal ...

@Flithor Nesse caso, aqui está o código de amostra prometido:

`` `c #
using System;
using System.Collections.Generic;
using System.Diagnostics;
usando Microsoft.EntityFrameworkCore;
usando Microsoft.Extensions.Logging;
usando Pomelo.EntityFrameworkCore.MySql.Infrastructure;

namespace IssueConsoleTemplate
{
public class IceCream
{
public int IceCreamId {get; definir; }
public string Name {get; definir; }
}

public class Context : DbContext
{
    public DbSet<IceCream> IceCreams { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseMySql(
                "server=127.0.0.1;port=3306;user=root;password=;database=Issue1279",
                b => b.ServerVersion("8.0.21-mysql")
                      .CharSetBehavior(CharSetBehavior.NeverAppend))
            .UseLoggerFactory(
                LoggerFactory.Create(
                    b => b.AddConsole()
                        .AddFilter(level => level >= LogLevel.Information)))
            .EnableSensitiveDataLogging()
            .EnableDetailedErrors();
    }
}

internal static class Program
{
    private static void Main()
    {
        using var context = new Context();

        context.Database.EnsureDeleted();
        context.Database.EnsureCreated();

        var tableNames = GetTableNames(context);

        Trace.Assert(tableNames.Contains("IceCreams"));
    }

    private static List<string> GetTableNames(DbContext context)
    {
        // EF Core will close the connection automatically for us, when we ensure, that it is EF Core itself that is
        // responsible for opening the database connection. We can ensure that by calling `OpenConnection()` first.
        context.Database.OpenConnection();

        var connection = context.Database.GetDbConnection();

        using var command = connection.CreateCommand();
        command.CommandText = @"select `TABLE_NAME`

de INFORMATION_SCHEMA . TABLES
onde TABLE_SCHEMA = banco de dados (); ";

        var tableNames = new List<string>();

        using var reader = command.ExecuteReader();
        while (reader.Read())
        {
            tableNames.Add((string) reader["TABLE_NAME"]);
        }

        return tableNames;
    }
}

}
`` `

Todos 4 comentários

Sim, uma consulta personalizada como SHOW TABLES; funcionaria. Faça esta pergunta no Stack Overflow para obter mais ajuda, pois os problemas não são para esse propósito.

@Flithor Vou responder a você com alguns códigos de amostra no Stack Overflow, assim que você postar sua pergunta lá. Por favor, use a tag pomelo-entityframeworkcore-mysql , então serei notificado (é uma questão relacionada ao MySQL e ao EF Core, então perto o suficiente).

Uh oh, talvez eu não possa, eu tenho um limite de perguntas no Stack Overflow. - Muita pergunta pessoal ...
(Vou editar o título para ajudar os outros)

Uh oh, talvez eu não possa, eu tenho um limite de perguntas no Stack Overflow. - Muita pergunta pessoal ...

@Flithor Nesse caso, aqui está o código de amostra prometido:

`` `c #
using System;
using System.Collections.Generic;
using System.Diagnostics;
usando Microsoft.EntityFrameworkCore;
usando Microsoft.Extensions.Logging;
usando Pomelo.EntityFrameworkCore.MySql.Infrastructure;

namespace IssueConsoleTemplate
{
public class IceCream
{
public int IceCreamId {get; definir; }
public string Name {get; definir; }
}

public class Context : DbContext
{
    public DbSet<IceCream> IceCreams { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseMySql(
                "server=127.0.0.1;port=3306;user=root;password=;database=Issue1279",
                b => b.ServerVersion("8.0.21-mysql")
                      .CharSetBehavior(CharSetBehavior.NeverAppend))
            .UseLoggerFactory(
                LoggerFactory.Create(
                    b => b.AddConsole()
                        .AddFilter(level => level >= LogLevel.Information)))
            .EnableSensitiveDataLogging()
            .EnableDetailedErrors();
    }
}

internal static class Program
{
    private static void Main()
    {
        using var context = new Context();

        context.Database.EnsureDeleted();
        context.Database.EnsureCreated();

        var tableNames = GetTableNames(context);

        Trace.Assert(tableNames.Contains("IceCreams"));
    }

    private static List<string> GetTableNames(DbContext context)
    {
        // EF Core will close the connection automatically for us, when we ensure, that it is EF Core itself that is
        // responsible for opening the database connection. We can ensure that by calling `OpenConnection()` first.
        context.Database.OpenConnection();

        var connection = context.Database.GetDbConnection();

        using var command = connection.CreateCommand();
        command.CommandText = @"select `TABLE_NAME`

de INFORMATION_SCHEMA . TABLES
onde TABLE_SCHEMA = banco de dados (); ";

        var tableNames = new List<string>();

        using var reader = command.ExecuteReader();
        while (reader.Read())
        {
            tableNames.Add((string) reader["TABLE_NAME"]);
        }

        return tableNames;
    }
}

}
`` `

Esta página foi útil?
0 / 5 - 0 avaliações