【问题标题】:EF Core 2.0 Npgsql : 42P01EF 核心 2.0 Npgsql:42P01
【发布时间】:2019-03-06 11:30:57
【问题描述】:

我正在使用 EF Core 2.0 学习 Postgresql

我不断收到此错误。我在谷歌上搜索过,但我找不到正确的答案。

这是我的代码的一些细节; 启动.CS;

public void ConfigureServices(IServiceCollection services)
    {
        var connectionString =  @"User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=Test;";

        services.AddEntityFrameworkNpgsql()
            .AddDbContext<DataContext>(options => options.UseNpgsql(connectionString));


        services.AddMvc();
    }

和数据上下文;

public class DataContext : DbContext
{
    public DataContext(DbContextOptions<DataContext> options) : base(options)
    {
    }

    public DbSet<Questions> Questions { get; set; }

}

还有我的模特;

public class Questions
{
    public int Id { get; set; }

    public int studentId { get; set; } 

    public string Title { get; set; }

    public int Votes { get; set; }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: c# postgresql asp.net-core-mvc entity-framework-core


    【解决方案1】:

    好的,已修复。 我认为 postgresql 是区分大小写的。

    当我更改模型等于数据库问题时解决了。

    这是我的新模型。

    【讨论】:

      【解决方案2】:

      偶然发现了这个问题,虽然迟到了,但我也体验过 Oracle(使用Oracle.EntityFrameworkCore,我需要大写字母)和 postgres(使用Npgsql.EntityFrameworkCore,我需要小写字母)的大小写敏感度/列名。

      我将在此处添加我的解决方案,以便将来对其他人有所帮助。我通过创建一个扩展方法来解决如下:

      public static void LowercaseRelationalTableAndPropertyNames(this ModelBuilder modelBuilder) 
      {
          foreach (var entity in modelBuilder.Model.GetEntityTypes())
          {
              entity.Relational().TableName = entity.Relational().TableName.ToLowerInvariant();
      
              foreach (var property in entity.GetProperties())
              {
                  property.Relational().ColumnName = property.Relational().ColumnName.ToLowerInvariant();
              }
          }
      }
      

      并使用如下:

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

      它允许使用混合大小写构建模型并在运行时转换如下:

      public class Questions
      {
          public int Id { get; set; }
          public int StudentId { get; set; }
      }
      

      注意,对于 EFCore 3.0,扩展方法变化如下:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-25
        • 1970-01-01
        相关资源
        最近更新 更多