我有这个:
public void AssertReadWorks<T>(
IRepository<T> repository,
T entity,
Expression<Func<T, T, bool>> keyComparer) where T : class
{
entity = repository.GetAll().Single(x => x.Id == entity.Id);
}
[TestMethod]
public void ReadTest_DataFieldGroup()
{
AssertReadWorks(
_unitOfWork.DataFieldSetRepository,
new DataFieldSet { Label = "test", Title = "test" },
(a, b) => a.Id == b.Id);
}
这不会编译,因为不知道 T 具有 Id 属性。请注意,该keyComparer
参数目前未使用。我想使用 keyComparer 参数(或另一个适当的参数)来动态生成谓词Single()
:
Expression<Func<T, bool>> keyComparingPredicate =
x => a predicate that compares the key of x with the key of `entity`;
entity = repository.GetAll().Single(keyComparingPredicate);
关键是不是所有的 T 都会有 Id 属性,有些会有不同的名字,有些会有复合键。AssertReadWorks()
如果它不是通用的,则原件可以正常工作。问题只是在一般情况下动态构建谓词。如果它可以用与 keyComparer 参数不同的东西来完成,我很好。
有任何想法吗?:)