Search code examples
npgsql

Create Schema using EF Core failing for npgsql


I’m trying to create a schema using context.

Database.ExecuteSqlCommand(“CREATE SCHEMA @p0”, <schemaNameParameter>)

It is giving the below error:

42601: Syntax error at or near $1

I tried other solutions given for similar question for DML, but they did not work in my case.


Solution

  • I found a solution, may not be very elegant, but works:

    var con = _context.Database.GetDbConnection();
    con.Open();
    try
    { 
        using (var cmd = con.CreateCommand())
        {
            cmd.CommandText = $"CREATE SCHEMA IF NOT EXISTS \"<schemaName\">";
            await cmd.ExecuteNonQueryAsync();
        }
    }
    finally
    {
        con.Close();
    }
    

    PS: Still trying to find a solution which takes a parameter rather than inline value for the schema name. (Note: I'm using regex validation before executing this command to ensure there is no injection attempt)