Eleazar Celis
Eleazar Celis

Reputation: 33

Is possible to use lambda expression in linq to sql?

I wonder if you can do something like this:

    public List<T> FindOrder<T>(Expression<Func<T, bool>> predicate) where T : class
    {
        DbSet<Preventivos> preventivos = this.Preventivos;

        return (from p in preventivos
                where predicate
                select new...

Upvotes: 1

Views: 1220

Answers (3)

James Curran
James Curran

Reputation: 103495

To complement Jon's answer, here's a selection from some actual working code (in use @ www.NJtheater.com) allowing you to look a venue by ID# or name

    public void Display(int id)
    {
        Display(ven => ven.VenueID == id);
    }

    public void Display(string name)
    {
        Display(ven => ven.Shortname == name);
    }

    public void Display(Expression<Func<Venue, bool>> whereClause)
    {
        Venue venue = db.Venues.Where(whereClause).FirstOrDefault();

           /// etc

Upvotes: 0

D Stanley
D Stanley

Reputation: 152521

Not with an Expression. If your parameter were just a Func<T, bool> then you could treat predicate as a delegate:

     return (from p in preventivos
            where predicate(p)
            select new ...

Which will probably fail when the provider tries to convert to SQL since it needs have the metadata of an Expression to generate the equivalent SQL.

You could try to Compile the expression first to convert it to a Func<T, bool>:

    return (from p in preventivos
            where predicate.Compile()(p)
            select new ...

Which will compile but may still fail at runtime when the query provider tries to convert it to SQL.

So unless you're really hung up on using query syntax, method syntax would be much cleaner:

return preventivos.Where(predicate)
                  .Select(p => new ...);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500105

Not like that, no - but you can write:

return preventivos.Where(predicate).Select(...);

... although your code example seems to be unclear as to whether this is really generic or whether it only deals with Preventivos.

The point is that the query expression you've provided would add an extra "wrapper" layer:

return preventivos.Where(p => predicate)
                  .Select(p => new { ... });

... whereas you want to pass the predicate expression tree directly to the Where call.

Upvotes: 4

Related Questions