美文网首页
EFCore使用PostgreSql问题记录

EFCore使用PostgreSql问题记录

作者: Messix_1102 | 来源:发表于2024-01-24 17:31 被阅读0次

1. EFCore 配置

  • 安装Npgsql.EntityFrameworkCore.PostgreSQL
  • 连接字符串:
Server=127.0.0.1;Port=5432;Database=testdb;User Id=zhangsan;Password=mima;Pooling=true;Maximum Pool Size=512;
  • DBContext注入
    public class DbContextInjection
    {
        public static void Configure(IServiceCollection serviceCollection)
        {
            serviceCollection.AddPooledDbContextFactory<MyDbContext>(options =>
            {
                 options.UseNpgsql(ConfigReader.GetConfig("ConnectionStrings:DefaultConnection"));
#if DEBUG
                 options.UseLoggerFactory(logFactory);
#endif
            }, poolSize: 500);
        }

        private static readonly ILoggerFactory logFactory = LoggerFactory.Create(build =>
        {
            build.AddConsole();
            build.AddDebug();
        });
    }
  • 模型配置
public class ConfigParamConfiguration : IEntityTypeConfiguration<ConfigParam>
{
    public void Configure(EntityTypeBuilder<ConfigParam> builder)
    {
        // 第一个参数为表名, 第二个参数为Schema名称
        builder.ToTable("System_ConfigParam", "dmp")
            .HasKey(o => o.Id);
    }
}
  • 执行自定义SQL
public int ExecuteNonQuery(string sqlStr, NpgsqlParameter[] sqlParameters)
{
    using MyDbContext dbContext = dbContextFactory.CreateDbContext();
    NpgsqlConnection connection = (NpgsqlConnection)dbContext.Database.GetDbConnection();
    connection.Open();
    try
    {
        using NpgsqlCommand command = new NpgsqlCommand(sqlStr, connection);
        foreach (var parameter in sqlParameters)
        {
            command.Parameters.Add(parameter);
        }
        int result = command.ExecuteNonQuery();
        return  result;
    }
    finally 
    { 
        connection.Close(); 
    }
}

2. PostgreSql 与常见的MySql, SqlServer 等数据库不同

丫大小写敏感!!!

  • 假如创建表脚本是这么写的
CREATE TABLE IF NOT EXISTS dbo."SystemConfig"
(
    "Id" SERIAL PRIMARY KEY,
    "ConfigKey" VARCHAR(100),
    "ConfigValue" VARCHAR(500) NOT NULL
);

注意: dbo是pgsql的schema名称, "SystemConfig" 是表名

  • 如果查询SQL这么写, 就报错了
SELECT Id, ConfigKey, ConfigValue
FROM dbo.SystemConfig
  • 正确的写法是跟建表脚本一样, 加上引号
SELECT "Id", "ConfigKey", "ConfigValue"
FROM dbo."SystemConfig"

而且Schema名称, 表名和字段名大小写也不能错, 这也是Npgsql EFCore生成SQL的规则, 如果你的表创建的时候没有按照上面说的规则添加引号, 那么增删改查会报这样的错: relation "XXX" does not exist

3. 特殊语法规则

  • 每段SQL之后要加分号, 不然会报错

4. postgreSql 与 C# 类型对应

  • C#: Datetime => pgsql: TIMESTAMP
    如果这两种类型转换报错, 需要在主程序Main方法中加入下面这两句:
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
  • C#: bool => pgsql: BOOLEAN
    如果数据库设置bit, C#数据类型是bool, 丫不能自动解析, 会报错

相关文章

网友评论

      本文标题:EFCore使用PostgreSql问题记录

      本文链接:https://www.haomeiwen.com/subject/tedmodtx.html