I have a LINQ query which retrieves values from 2 tables as such:
Dim query = From t1 In context.table1
Join t2 In context.table2
On t1.ID Equals t2.ID
Select t1, t2
table1
has an unmapped property of type table2
, which I would like to populate using the selected t2
value.
I've tried using the following:
For Each val In query.AsEnumerable()
val.t1.t2property = val.t2
Next
When I run the code, the t2property
is not being populated (presumably because the query hasn't loaded due to lazy loading (feel free to correct me here)).
The added complexity is that I have to use this query as a source column in another query to the database.
Is there a way to populate the unmapped t2property
from the select
in the initial query?
Or is there something I can do to assign the val.t1.t2property = val.t2
?
When you assign a variable a LINQ query, the variable is not assigned the results of the query but a representation of the query that can be executed later. When you do something that causes the query to be executed, the objects returned from the query are instantiated from the database and created in memory.
When you do the For Each
loop over the query
(the AsEnumerable()
does nothing useful here), the query is executed, objects for table1
and table2
are created, and anonymous objects are created from those containing t1
and t2
.
After you exit the For Each
loop, all those objects are thrown away, and the next time you execute query
, new data is pulled from the database and new objects created.
If you need to hold onto and modify or query the objects in memory, you need to change the type of query
to something that will hold the objects. Typically that will be an Array
or List
, in general, ToList
is the better option.
Dim query = (From t1 In table1
Join t2 In table2 On t1.ID Equals t2.ID
Select t1, t2).ToList()
For Each val In query
val.t1.t2property = val.t2
Next