Search code examples
c#hibernatenhibernatenhibernate-mapping

Mapping: Default value across databases


I'm mapping a class with NHibernate, but I use the same map over 2 different databases. This works on Sybase Anywhere, but doesn't work on SQLite.

This is my map class:

public FooMap()
{
    Property(x => x.Date, map =>
    {
        map.Column(c => c.Default("now(*)"));
        map.Generated(PropertyGeneration.Insert);
        map.NotNullable(true);
    });
}

and this is the mapper:

public class Provider
{
    public void AddMappings(ModelMapper mapper)
    {
        mapper.AddMappings(Assembly.GetAssembly(typeof(BaseMap)).GetExportedTypes().Where(x => x.Name.EndsWith("Map")));
    }
}

SQlite doesn't have NOW function, so this cause a error when Hibernate try to create this table.

How can I insert a default value according with the database?


Solution

  • I'm using StructureMapMVC so i did this:

    var db = DependencyResolver.Current.GetService<Provider>();
    
    if (db == null)
    {
        throw new NullReferenceException("Service Provider not found.");
    }
    
    if (db is SybaseProvider)
    {
        map.Column(c => c.Default("now(*)"));
    }
    else // SQLite
    {
        map.Column(c => c.Default("CURRENT_TIMESTAMP"));
    }
    map.Generated(PropertyGeneration.Insert);
    map.NotNullable(true);
    

    Worked for me.