如何使用Dapper将字符串列映射到Uri属性的最清晰的方法是什么?
到目前为止,这是我能想到的最简洁的方法(使用ITypeMap功能):
查询:
SELECT * FROM TableWithAStringAddressColumn
POCO:
public class MyPoco
{
[ColumnSetter("DapperAddress")]
public Uri Address { get; set; }
private string DapperAddress { set { this.Address = new Uri(value); } }
}
扩展:
partial class SqlMapper
{
public static void InitializeTypeMaps()
{
SqlMapper.SetTypeMap(
typeof(MyPoco),
new CustomPropertyTypeMap(typeof(MyPoco), SqlMapper.CustomSetterMapper));
// call out every other class that needs this kind of mapping
}
public static Func<Type, string, PropertyInfo> CustomSetterMapper =
(type, columnName) =>
{
PropertyInfo prop = type
.GetProperties()
.FirstOrDefault(p => string.Equals(columnName, p.Name, StringComparison.OrdinalIgnoreCase));
if (prop != null)
{
// find out if we need to use a different setter
ColumnSetterAttribute setterAttribute = prop.GetCustomAttributes(false).OfType<ColumnSetterAttribute>().LastOrDefault();
if (setterAttribute != null)
{
PropertyInfo setterProp = type
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.FirstOrDefault(p => string.Equals(setterAttribute.Setter, p.Name, StringComparison.OrdinalIgnoreCase));
if (setterProp == null)
{
throw new InvalidOperationException(string.Format("Setter property misconfigured (Property={0}, Setter={1})", prop.Name, setterAttribute.Setter));
}
else
{
prop = setterProp;
}
}
}
return prop;
};
}
自定义属性:
public class ColumnSetterAttribute : Attribute
{
public string Setter { get; set; }
public ColumnSetterAttribute(string setter)
{
this.Setter = setter;
}
}
[编辑] 我正在寻找一种解决方案,可以在不需要在所有查询中调用所有列的情况下使用(我希望找到一种可以使用 SELECT *
的解决方案)。
SELECT Column1, Column2, SomeUri AS Mapper FROM TableName
。但是,我正在寻找一种不必在所有查询中都调用所有列的解决方案。 - ClayUri SomeUri { get { ... } }
,那么SELECT *,SomeUri AS Mapper
技巧确实有效。如果您将SomeUri
设置为自动属性public Uri SomeUri { get; set; }
,则无法使用该技巧。 - Clay