使用 dapper 为 id 创建约定

本文关键字:创建 约定 id dapper 使用 | 更新日期: 2023-09-27 18:37:11

我想创建一个约定来将名为"Id"的列设置为主键,我一直在查看文档,到目前为止,我已经鼓励逐个类手动执行此操作,例如:与多梅尔:

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

我想要更像:

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

它可以是 dommel 或 dapper 扩展或任何其他扩展,我只是这个实现很流畅。

有什么建议吗?谢谢!

使用 dapper 为 id 创建约定

Dommel 允许您创建自定义IKeyPropertyResolver

您的实现如下所示:

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

应该在应用程序启动时使用以下代码行注册:

DommelMapper.SetKeyPropertyResolver(new CustomKeyPropertyResolver());

你不需要Dapper.FluentMap(或Dapper.FluentMap.Dommel)。另请参阅:文档。