frenchie
frenchie

Reputation: 51927

does linq-to-sql handle dynamic queries?

I'm building a dynamic query. Basically, a function receives an object MyParams whose properties are the parameters; I'm creating the Where clauses based on the MyParams object and returning a list of anonymous type.

So, does L2SQL support creating a dynamic query? I have a data context that already works for other queries. Depending on the parameters, I need to access some tables sometimes so do I also need to write the From clauses dynamically or should I just include all the tables and focus only on the where clauses?

Thanks.

Upvotes: 2

Views: 338

Answers (2)

Alex Aza
Alex Aza

Reputation: 78457

You can do something like this if this is what you want to:

        var baseQuery = dataAccess.Table1.Where(arg => arg.Field1 = 1);

        if (parameter[1] = true)
        {
            baseQuery = baseQuery.Where(arg => arg.Field2 = 'Test');
        }

        if (parameter[2] = true)
        {
            baseQuery = 
                from x in baseQuery
                join y in dataAccess.Table2 on
                    x.Id equals y.Id
                where y.Field3 = 'Something'
                select x;
        }

        return baseQuery.ToList();

Upvotes: 3

Rune FS
Rune FS

Reputation: 21742

You should be able to use my answer to another question. Your question is not an exact copy yours is more generic but the why to solve the problem is exactly the same.

Upvotes: 1

Related Questions