Introduction
PropertyMapper<T> 是一个帮助类,允许映射对象属性到string keys.这也允许把新的值赋值给这些string keys.
开始写这些代码是用在EntityFramework Code-First.我也一个带有很多大写名称或下划线的数据列的表结构,
我不希望重新定义表结构 ,所以我决定写一个帮助类把对象属性映射到string keys, 从对象实例中分离值
并且快速映射回原有的original string keys,格式化成字典。
Source Code
public sealed class PropertyMapper<T>
{
private readonly Dictionary<string, string> m_maps = new Dictionary<string, string>();
private readonly Dictionary<string, string> m_props = new Dictionary<string, string>();
private static string GetPropertyName<TReturn>(Expression<Func<T, TReturn>> property)
{
var expr = property.Body as MemberExpression;
if (expr == null)
throw new InvalidOperationException("Invalid property type");
return expr.Member.Name;
}
public void MapProperty<TReturn>(Expression<Func<T, TReturn>> property, string mapTo)
{
var propName = GetPropertyName(property);
m_maps[mapTo] = propName;
m_props[propName] = mapTo;
}
public string GetPropertyMap<TReturn>(Expression<Func<T, TReturn>> property)
{
return GetPropertyMap(GetPropertyName(property));
}
public string GetPropertyMap(string property)
{
string result;
return m_props.TryGetValue(property, out result) ? result : null;
}
public object GetPropertyValue(T instance, string property)
{
string result;
if (!m_maps.TryGetValue(property, out result))
return null;
return typeof (T).GetProperty(result).GetValue(instance, null);
}
public IDictionary<string, object> GetPropertyValues(T instance)
{
return m_maps
.Select(x => new {Name = x.Key, Value = typeof (T).GetProperty(x.Value).GetValue(instance, null)})
.Where(x => x.Name != null && x.Value != null)
.ToDictionary(x => x.Name, x => x.Value);
}
}Using the Code
定义类:public sealed class Test
{
public string Foo { get; set; }
public string Bar { get; set; }
}使用:
var mapper = new PropertyMapper<Test>();
mapper.MapProperty(x => x.Foo, "PROP-FOO");
mapper.MapProperty(x => x.Bar, "PROP-BAR");
var t = new Test {Foo = "Value-Foo", Bar = "Value-Bar"};
Console.WriteLine("Single property:");
var propMap = mapper.GetPropertyMap(x => x.Foo);
Console.WriteLine("{0}={1}", propMap, mapper.GetPropertyValue(t, propMap));
Console.WriteLine();
Console.WriteLine("All properties:");
foreach (var item in mapper.GetPropertyValues(t))
Console.WriteLine("{0}={1}", item.Key, item.Value);输出:
Single property:
PROP-FOO=Value-Foo
All properties:
PROP-FOO=Value-Foo
PROP-BAR=Value-Bar
本文介绍了一个名为PropertyMapper的实用类,它能够将对象属性映射为字符串键,并允许为这些键设置新值。该类特别适用于EntityFramework Code-First环境中,用于处理具有大写名称或下划线的数据库表结构。
4386

被折叠的 条评论
为什么被折叠?



