pedrommuller
pedrommuller

Reputation: 16066

Create a convention for ids using dapper

I'd like to create a convention to set the column that are named as "Id" to be primary key, I've been looking at the documentacion and so far I've foud ony to do it manually class by class like: with dommel:

public class ProductMap : DommelEntityMap<TEntity>
{
    public ProductMap()
    {
        Map(p => p.Id).IsKey();
    }
}

I'd like something more like:

    public ConventionMap()
    {
        Properties<int>().Where(p=>p.Name.ToLower()=="id").isKey();
    }

it could be dommel or dapper extensions or any other, I just this implementation to be fluent.

any advice? thanks!

Upvotes: 2

Views: 1378

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46591

Dommel allows you to create a custom IKeyPropertyResolver.

Your implementation would look like:

public class CustomKeyPropertyResolver : DommelMapper.IKeyPropertyResolver
{
    public PropertyInfo ResolveKeyProperty(Type type)
    {
        return type.GetProperties().Single(p => p.Name.ToLower() == "id");
    }
}

Which should be registered at application start-up using this line of code:

DommelMapper.SetKeyPropertyResolver(new CustomKeyPropertyResolver());

You don't need Dapper.FluentMap (or Dapper.FluentMap.Dommel) for this. Also see: the documentation.

Upvotes: 2

Related Questions