Create a convention for ids using dapper

c# dapper dapper-extensions dommel

Question

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!

Accepted Answer

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.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why