Search code examples
entity-frameworknpgsql

Npgsql integration with Entity Framework Code First


I have a project using the last version of EF CF with PostgreSQL and Npgsql.

My model looks like:

[Table("mytable")]
public class MyTable
{
    [Column("id")]
    public int Id { get; set; }
    [Column("mycolumn")]
    public string MyColumn { get; set; }
}

And the database/tables/columns has lowercase names like:

CREATE TABLE mytable
{
    id serial,
    mycolumn character(50)
}

The Npgsql generates SQL commands with quotation marks so I must use the Data Annotations due the PostgreSQL characteristics, witch is annoying. However I would like to not use quotations delimited names in the database.

Is there a way to configure Npgsql to not include quotation marks when generate commands or force lowercase table/columns names in the generated SQL?


Solution

  • If I'm not missing something - you'd want some generic way of changing the naming convention for tables?

    The EF6 has the custom conventions feature - it's still not official version, but if it works for you, some links...

    http://entityframework.codeplex.com/wikipage?title=Custom%20Conventions

    In your case, you'd have to implement it for the class/Type I guess - e.g. (some pseudo code)...

    1) implement IConfigurationConvention<Type, EntityTypeConfiguration> (you can check the EF source for EntityConventionBase)

    2) In the Apply - change how the Table names are generated via configuration (ToTable()) - to something like .ToLowerCase()

    3) add to conventions...

    For example...

    public class SmallCapsEntitiesConfigurationConvention
        : IConfigurationConvention<Type, EntityTypeConfiguration>
    {
        public void Apply(Type memberInfo, Func<EntityTypeConfiguration> configuration)
        {
            configuration().ToTable(memberInfo.Name.ToLowerInvariant(), null);
        }
    }
    

    You can see one example here
    http://blog.cincura.net/233167-custom-conventions-in-entity-framework-6-helping-firebird/

    Otherwise, I have no idea about Npgsql / PostgreSQL - it did seem a bit 'raw' to me. But you can handle it on the EF side.