EFCore使用PostgreSql问题记录

2024-01-24  本文已影响0人  Messix_1102

1. EFCore 配置

Server=127.0.0.1;Port=5432;Database=testdb;User Id=zhangsan;Password=mima;Pooling=true;Maximum Pool Size=512;
    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);
    }
}
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" 是表名

SELECT Id, ConfigKey, ConfigValue
FROM dbo.SystemConfig
SELECT "Id", "ConfigKey", "ConfigValue"
FROM dbo."SystemConfig"

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

3. 特殊语法规则

4. postgreSql 与 C# 类型对应

AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
上一篇 下一篇

猜你喜欢

热点阅读