views:

995

answers:

2

Hi,

We need to generate LINQ queries which are 100% unknown during coding (design time). This is because the logic is available in our framework which is 100% separated from any data projects. For data we use LLBLGen generated data access code.

Normally by using invokes on the DLL, which we specify to the framework (not reference) we can create code to retrieve data. But now we need to do this by linq. How could we create a query like:

var q = from customer in m.Customer
        select new
        {                   
            customer.Number,
            customer.City,
            customer.CountryEntity.Name             
        };

from strings only. We would have 1 string called "customer" so we know we have to retrieve from Customer. Then we would have a string[] containing the fieldnames we want to retrieve. As you can see these columns could include complex types (related fields).

Any advice, especially in combination with LLBLGen, would be great!

Thanks, Gab

+1  A: 

I'm not sure if this is exactly what your looking for but Scott Gu has a post on his blog about using dynamic LINQ.http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

It may not do everything you need but it may get you some of the way.

EDIT. I was just having a look at some sample code that Scott Gu had, and found that it can do the select part that you need. Example(This is Scotts code):

Dim query = db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10). _
                OrderBy("CompanyName"). _
                Select("New(CompanyName as Name, Phone)")

As you can see the bottom bit has has a dynamic select.

Also to solve the problem of dynamically knowing which object to query at runtime, you could something like this:

 Sub query(Of T)(ByVal Myobject As IQueryable(Of T))
    Dim i = Myobject.Select("New(customer.Number)")
 End Sub

Then you could just do a little switch after you read the names from the database, like so:

Sub PassIt()
    Dim name = "customer"
    Select Case name
        Case "customer"
            query(m.Customer)
    End Select
End Sub

Hope this helps. Note! There would be a better way of doing the last part(passit method) but its to early in the morning to think of it.

Sorry the answer is in VB I should have done it in C#

Nathan W
I had found this too... but it's the 'select from' part that I need the most. Not the filtering of fields. Thanks anyway
Gabriël
A: 

I turned out to be the basis of the solution indeed!

Thanks.

See also: http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=14633

Gabriël