Search code examples
postgresqlentity-framework-6npgsql

Weird syntax Error while Inserting data to PostgreSQL using Entity Framework


Context:

    public MyContext() : base("POSTGRE_TestDB") //For PostreSQL
    {

    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("public");
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<testModel> testcase { get; set; }

Model:

[Table("test_table")]
public class testModel
{
    [Key]
    //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }
    public string test_name { get; set; }
}

My code:

var test = new testModel();
test.id = 10;
test.test_name = "test";
            try
            {
                //_context.Entry(test).State = EntityState.Added;
                _context.testcase.Add(test);
                _context.SaveChanges();
            }catch(...){...}


Querying the same database is working as usual. Problem comes when inserting the row. Error:

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> 
System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> 
Npgsql.NpgsqlException: ERROR: 42601: syntax error at or near "RETURNING"

I am not sure what's wrong with the syntax exactly of Postgres because of the EF. Can anybody tell me whats wrong here?


Solution

  • I checked the logs of Postgres. The insert statement executed by entity framework was :

    INSERT INTO "public"."test_table"("test_name") VALUES ('test') RETURNING "id"
    

    Nothing is wrong with this generated command by entity framework. The Postgres I am using is 8.0.1 which I guess doesn't support RETURNING keyword. I will have to find some way to exclude RETURNING from the insert query.