JorgeT
JorgeT

Reputation: 23

How to pass a func<> in linq to sql with a join

I have the following issue.

I want to pass a func as parameter so it can vary in the where statement.

   private IEnumerable<User> GetUser(int cant, Func<User, bool> userFilter, Func<Client, bool> ClientFilter)
    {
        return (from dcu in
                    _db.All<User>().Where(userFilter)
                join c in _db.All<Client>() on dcu.IdClient equals c.IdClient into temp
                from cli in temp.DefaultIfEmpty().Where(ClientFilter)
                select new {Usuer = dcu, Client = cli}).
            Take(cant).Select(uc => _usersMapper.Map(uc.User, uc.Client)).AsEnumerable();

    }

And the func should look like this

    public void GetUsers ()
    {
        GetUser(50, u => u.Email.Contains("[email protected]"), c=> true);
    }
    public void GetUsersFilterByClient ()
    {
        GetUser(50, u => true, c=> c.Password.Contains("MyPasssword"));
    }

Upvotes: 1

Views: 316

Answers (2)

eouw0o83hf
eouw0o83hf

Reputation: 9588

You need to lambda your Where into the filter function:

private IEnumerable<User> GetUser(int cant, Func<User, bool> filter)
{
    return (from dcu in _db.All<User>().Where(a => filter(a))
            join c in _db.All<Client>() on dcu.IdClient equals c.IdClient into temp
            from cli in temp.DefaultIfEmpty()
            select new {Usuer = dcu, Client = cli}).
        Take(cant).Select(uc => _usersMapper.Map(uc.User, uc.Client)).AsEnumerable();
}

Upvotes: 2

dotnetnate
dotnetnate

Reputation: 769

This is an example from a repository implementation I created - the Func approach should suffice:

protected override IEnumerable<ContentType> FindImpl(Func<ContentType, bool> matchPredicate)
{
    return _context.ContentTypes.Where(matchPredicate);
}

Upvotes: 0

Related Questions