I found many examples of generic repository using LINQ to SQL. However there is not enough examples about how to call these functions. Can you please provide an example about how to use the following functions by a client?
Note: My question is about the use of Func T,bool. What are the possible ways to use it?
Note: BankAccount is an entity.
class MyRepository<T> : IRepository<T> where T : class
{
..........
public IEnumerable<T> FindAll(Func<T,bool> predicate)
{
return Context.GetTable<T>().Where(predicate);
}
public T FindByID(Func<T,bool> predicate)
{
return Context.GetTable<T>().SingleOrDefault(predicate);
}
}
EDIT
Based on response, I used it as follows;
public RepositoryLayer.Account FindFirstAccount()
{
Func<RepositoryLayer.Account, bool> predicate = (p => p.AccountNumber == 1);
List<RepositoryLayer.Account> accList = (accountRepository.FindAll(predicate)).ToList();
return accList[0];
}
Note: List RepositoryLayer.Account accList = (List RepositoryLayer.Account) accountRepository.FindAll(predicate); will not work
There are a few ways to specify Func, which is in essence a
delegatewhich takes one parameter and returns a bool.The most convenient way in most situations is to specify it as a Lambda expression, such as:
The other ways of specifying Func are best described here.
EDIT:
To fix your latest error, you need the results as List. Remove your explicit cast and try: