我正在尝试实现Entity Framework的动态存储库。我注意到我们使用了很多这种模式:
public Dictionary<int, string> SelectSomething(IEnumerable<int> ids)
{
return entity
.Table
.Where(t => ids.Contains(t.IdField))
.Select(t => new {t.IdField, t.ValueField})
.ToDictionary(k => kIdField, v => v.ValueField);
}
基本上,选择并返回ID符合某种条件的字典。
我试图一般地重写这个方法。到目前为止,我已经签名了:
Dictionary<TKey, TValue> GetEntityKeyValue<TEntity, TKey, TValue>(
Expression<Func<TEntity, TKey>> keyExpression,
Expression<Func<TEntity, TValue>> valueExpression,
Expression<Func<TKey, bool>> keyPredicate)
where TEntity : class
{ ... }
基本上,我可以打电话给
var valueDict = GetEntityKeyValue<tbl_table, int, string>(t => t.IdField, t.ValueField, id => id > 1);
请帮我写 GetEntityKeyValue 方法。我知道它会以某种方式涉及动态表达,但我不知道如何写它。
答案 0 :(得分:1)
Select
语句,而且它会创建对匿名类型的投影,从而导致相应的Expression
建筑要求:
public Dictionary<TKey, TValue> GetEntityKeyValue<TEntity, TKey, TValue>
(
Func<TEntity, TKey> keySelector,
Func<TEntity, TValue> valueSelector,
Expression<Func<TEntity, bool>> keyPredicate
) where TEntity : class
{
return context.Set<TEntity>().Where(keyPredicate)
.ToDictionary(keySelector, valueSelector);
}