0

In a project that uses Linq2Sql I have the following tables:

+-------------+       +-------------+       
| Orders      |       | OrdItems    |       +-------------+
+-------------+       +-------------+       | Items       |
| OrderID  PK | 1---n | OrderID  PK |       +-------------+
| ...         |       | ItemID   PK | n---1 | ItemID   PK |
|             |       | Quantity    |       | Description |
+-------------+       | ...         |       | ...         |
                      +-------------+       +-------------+
                     

In a serarch form I need to let the user provide some criteria and perform a search in Orders. Then the user selects a single order within search results and this single order is passed to another form.

The search query is something like this:

dim searchResults = From o in myDataContext.Orders Where [...] Select o

Using default DataLoadOptions, at this point I have a list of orders where the OrdItems collection is Nothing for every order. This is fine because when I perform search I'm not interested in every detail of every order.

When the user selects a single order I would like to populate OrdItems collection with the related Items property.

What is the simplest/most efficient way to do this?

To retrieve OrdItems I could do this:

dim order = searchResults.First() ' The user actually selects an order
order.OrdItems.Tolist()

but then I have to cycle through every OrdItems to retrieve Items value.

I could customize DataLoadOptions this way:

dim dlo = New DataLoadOptions()
dlo.LoadWith(Of OrdItems)(Function(o) o.Items)
myDataContext.LoadOptions = dlo

Unfortunately I can't do this after the search query has run, and if I do this before then details are loaded for every order.

Another option would be to create a new DataContext with different LoadOptions so that OrdItems and Items are loaded along with Orders and perform another query for the selected order. However, this way Orders table is queried twice.

3
  • This may not be an option but, if you can, stop using L2S and use Entity Framework instead. There are many similarities but the most important difference is that L2S has not been actively developed for years now, whereas EF is being actively developed and will be for the foreseeable future. Commented Apr 17 at 2:59
  • If this action is the performed only when a user selects one particular order the overhead of re-finding the order by its primary key probably won't be noticeable. Commented Apr 17 at 14:58
  • Why not just retrieve the OrdItems in a new query? (I.e. via context.Orditems.) Commented Apr 18 at 7:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.