0

我正在使用 dapper 扩展并对类映射器有疑问。不幸的是,我的大多数表都需要对它们进行一些映射,例如不同的模式等。

所以我发现我通常会按照以下方式更换 DefaultMapper:

public Hierarchies HierarchyGetByName(string aName)
{
    Hierarchies result;

    using (SqlConnection cn = GetSqlConnection())
    {
        cn.Open();

        Type currModelMapper = DapperExtensions.DapperExtensions.DefaultMapper;
        try
        {
            DapperExtensions.DapperExtensions.DefaultMapper = typeof(HierarchiesMapper);
            IFieldPredicate predicate = Predicates.Field<Hierarchies>(f => f.Name, Operator.Eq, aName);
            result = cn.GetList<Hierarchies>(predicate).FirstOrDefault();
        }
        finally
        {
            DapperExtensions.DapperExtensions.DefaultMapper = currModelMapper;
        }


        cn.Close();
    }

    return result;
}

如果我访问 2 个表,那么我必须这样做两次。

有没有办法一次添加所有映射器类来表示一个集合,并根据正在访问的表选择正确的表?

4

1 回答 1

0

您可以在您的应用程序中添加一组将自定义重新映射到您的实体的类。例如,这 3 个空类将 PrefixDapperTableMapper 应用于 Profile 和 FileNotificationAdhocRecipient 类,而将 AnotherDifferentTypeOfDapperClassMapper 应用于 NotificationProfile。

public class ProfileMapper : PrefixDapperTableMapper<Domain.Entities.Profile>
{
}

public class FileNotificationAdhocRecipientMapper : PrefixDapperTableMapper<Domain.Entities.FileNotificationAdhocRecipient>
{
}

public class NotificationProfileMapper : AnotherDifferentTypeOfDapperClassMapper<Domain.Entities.NotificationProfile>
{
}

and your actual mapping code exists in separate mappers (I've not shown AnotherDifferentTypeOfDapperClassMapper but that would be similar to below)

public class PrefixDapperTableMapper<T> : ClassMapper<T> where T : class
{
    public PrefixDapperTableMapper()
    {
        AutoMap();
    }

    //name or schema manipulations in some overrides here. 
}

As long as they're in the same assembly, DapperExtensions will find and use them or you can set the mapping assembly with code similar to:

DapperExtensions.DapperExtensions.SetMappingAssemblies({ typeof(ProfileMapper ).Assembly })
于 2016-08-25T11:40:43.800 回答