1

I have seen generic repository pattern here. I am trying to add generic select clause that i want to send as argument from calling function. I modified

public T GetSingle(Expression<Func<filter, bool>> filter) to 
public T GetSingle(Expression<Func<filter, bool>> filter,Expression<Func<T, T>> Selct)

Now I want to call this method. How should i send my select expression

return rep.GetSingle(p => p.Slug == slug,???)
Community
  • 1
  • 1
Tassadaque
  • 8,129
  • 13
  • 57
  • 89
  • 1
    We don't know what you're trying to achieve, which makes it rather tricky to know what argument you want to pass. Are you sure you really want an `Expression>` rather than the ability to change the result type? (`Expression>`) – Jon Skeet Jun 27 '12 at 05:42
  • Actually i want to send a field name from repository and my query should return that field rather than the whole object – Tassadaque Jun 27 '12 at 05:45
  • You want to pass in the field name as a *string*, or in a lambda expression? (Please read http://tinyurl.com/so-hints and edit your question so we don't need to keep going back and forth.) – Jon Skeet Jun 27 '12 at 05:46
  • 1
    `Expression>` would take T as input and return T as output without giving you ability to select specific properties from T. – Muhammad Adeel Zahid Jun 27 '12 at 05:49

2 Answers2

3

Currently your method can't change the result type. I suspect that's not what you want. I would expect you'd want your method to be generic, e.g.

public TResult GetSingle<TResult>(Expression<Func<T, bool>> filter,
                                  Expression<Func<T, TResult>> projection)

You'd then call that with something like this:

// The type argument is inferred from the second lambda expression
string x = repository.GetSingle(p => p.Slug == slug, p => p.FirstName);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • and you can also use it like `repository.GetSingle(p=>p.Slug == slug, p=>new{p.FirstName, p.SecondName})`. – Muhammad Adeel Zahid Jun 27 '12 at 05:51
  • It is giving me error on TResult. saying type or namespace not found – Tassadaque Jun 27 '12 at 05:56
  • @Tassadaque: Are you sure you copied my change to the method signature correctly? `TResult` is a generic type parameter *of the method*. (As it happens, I'd got the return type of the method wrong, but that wouldn't explain the error you saw.) And yes, you can call it for an anonymous type. – Jon Skeet Jun 27 '12 at 05:58
0

Your second argument in the method must be another lambda where the input is a T and it must return a T.

cjk
  • 45,739
  • 9
  • 81
  • 112