使用CustomPropertyTypeMap映射特定属性 [英] Using CustomPropertyTypeMap to map specific properties

查看:241
本文介绍了使用CustomPropertyTypeMap映射特定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类需要将一个或两个属性(在几十个属性中)映射到具有不同列名的表上的列。当数据库中只有两个与列名称不同时,我不想映射所有属性。

I have a couple of classes that need to have one or two properties (out of several dozen) mapped to a column on a table that has a different column name. I don't want to map all of the properties, when only two differ from the column names in the database.

我无法在所有的属性上找到合适的文档可与CustomPropertyTypeMap一起使用的各种映射选项,它们都仅显示了使用CustomPropertyTypeMap映射整个对象的方式(Dapper测试类也是如此)。当我使用以下命令时:

I can't find decent docs on all of the various mapping options that can be used with the CustomPropertyTypeMap, they all just show mapping the entire object with the CustomPropertyTypeMap (as does the Dapper tests class). When I use the following:

// Set up custom repository parameter mappings.
var map = new CustomPropertyTypeMap(typeof(T),
    (type, columnName) => type
        .GetProperties()
        .FirstOrDefault(
            prop => prop.GetCustomAttributes(false)
                .OfType<RepositoryParameterAttribute>()
                .Any(attr => attr.ParameterName == columnName)));

Dapper.SqlMapper.SetTypeMap(typeof(T), map);

// Query the database
items = await databaseConnection.QueryAsync<T>(
    storedProcedure,
    itemParameters,
    commandType: CommandType.StoredProcedure,
    transaction: transaction);

未使用RepositoryParameterAttribute装饰的属性返回null(或0)。我可以使用它来映射特定的属性,然后让Dapper合并剩余的非装饰属性,还是我需要做一些自定义的事情?

The properties that are not decorated with a RepositoryParameterAttribute return null (or 0). Can I use this to map just specific properties and let Dapper hydrate the remaining, non-decorated attributes, or am I going to have to do something custom?

谢谢。 / p>

Thanks.

推荐答案

Dapper .FluentMap 允许您配置从POCO属性到列表的映射。它使用 CustomPropertyTypeMap 并使用 DefaultTypeMap 作为后备。

Dapper.FluentMap allows you to configure mappings from POCO properties to column tables. It does this by using the CustomPropertyTypeMap and using the DefaultTypeMap as fallback.

它可以作为 NuGet包使用,但是您也可以看看,看看我如何实现 CustomerPropertyTypeMap 并为自己创建一个更简单的实现。

It's available as NuGet package, but you could also take a look at the source and see how I implemented the CustomerPropertyTypeMap and create a more simple implementation for yourself.

这篇关于使用CustomPropertyTypeMap映射特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆