简体   繁体   中英

Npgsql.PostgresException: relation "tablename" does not exist'

I have the following code, using Npgsql version 4.0.4.

var cmd = new NpgsqlCommand("INSERT INTO TableName (Id, DateTime, Dummy) VALUES (@id, @datetime, @dummy)", con);
cmd.Parameters.AddWithValue("id", new Guid());
cmd.Parameters.AddWithValue("datetime", DateTime.Now.ToString());
cmd.Parameters.AddWithValue("dummy", "foo");

I already created the table using Entity Framework in another program. However, I get the following error:

Npgsql.PostgresException: '42P01: relation "tablename" does not exist'

I tried putting public before my tablename, and the database name before my tablename.

I think I've seen this before, where EF Core suggested a table did not exist. In my case, due to table names being lowercase in Postgres (and in Oracle, uppercase)

Possibly try to lowercase your table names?

    public static class DataContextExtensions
    {
        public static void LowercaseRelationalTableAndPropertyNames(this ModelBuilder modelBuilder)
        {
            foreach (var entity in modelBuilder.Model.GetEntityTypes())
            {
                entity.SetTableName(entity.GetTableName().ToLowerInvariant());

                foreach (var property in entity.GetProperties())
                {
                    property.SetColumnName(property.GetColumnName().ToLowerInvariant());
                }
            }
        }
    }

... and in your DataContext...

    public class DataContext : DbContext
    {

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.LowercaseRelationalTableAndPropertyNames();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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