我有一个通用的存储库实现,它允许传递一个选择器来声明实体的主键属性:
public abstract class RepositoryBase<TEntity, TKey>
where TEntity : class
{
private readonly Func<TEntity, TKey> _keySelector;
protected Func<TEntity, TKey> KeySelector {
get {
return _keySelector;
}
}
protected RepositoryBase(Func<TEntity, TKey> selector) {
_keySelector = selector;
}
}
......可以像这样使用:
public class UserRepository : RepositoryBase<User, Guid>
{
public UserRepository()
: base((user) => user.Id)
{
}
}
我现在已经在内存存储库中实现了来进行一些单元测试,我想为每个持久化的实体生成一个新的标识。如果实体没有密钥的公共访问器,我已经创建了一个扩展方法来使用反射设置属性。
public static void SetProperty<T, TProperty>(this T instance, Expression<Func<T, TProperty>> selector,
TProperty newValue)
where T : class
{
if (instance == null)
throw new ArgumentNullException("instance");
if (selector == null)
throw new ArgumentNullException("selector");
var propertyInfo = selector.GetMember() as PropertyInfo;
if (propertyInfo == null)
throw new InvalidOperationException();
propertyInfo.SetValue(instance, newValue);
}
我现在的问题是:如何使用 KeySelector 作为表达式来设置主键值?有没有办法转换它?或者有更好的方法来实现我正在尝试的目标吗?
像这样?这甚至有意义吗?:protected override void AddItem(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
var id = default(TKey);
if (GetPrimaryKey(entity).Equals(default(TKey)))
{
id = _identifierGenerator.Generate();
entity.SetProperty(x => GetPrimaryKey(x), id); // <----
}
_items[id] = entity;
}
上面使用的一些方法:
public TKey GetPrimaryKey(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
return KeySelector(entity);
}
public static MemberInfo GetMember<T, TProperty>(this Expression<Func<T, TProperty>> expression)
{
var memberExp = RemoveUnary(expression.Body);
return memberExp == null ? null : memberExp.Member;
}
private static MemberExpression RemoveUnary(Expression toUnwrap)
{
var unwrap = toUnwrap as UnaryExpression;
if (unwrap != null)
{
return unwrap.Operand as MemberExpression;
}
return toUnwrap as MemberExpression;
}
答案 0 :(得分:3)
你基本上不能 - 没有任何有用的方式。解决方案似乎很简单 - 改为改变你的属性类型:
private readonly Expression<Func<TEntity, TKey>> _keySelector;
protected Expression<Func<TEntity, TKey>> KeySelector {
get {
return _keySelector;
}
}
protected RepositoryBase(Expression<Func<TEntity, TKey>> selector) {
_keySelector = selector;
}
您仍然可以使用lambda表达式初始化属性,如果确实需要,可以将表达式树编译为委托。