vcRobe vcRobe - 19 days ago 5
C# Question

LINQ Join returning IQueryable

I've a relationship between 3 tables like this

enter image description here

I wanna have a method that given a parameter of type table1 and the DbContext I get all the related rows from table3 passing through table2

Here's my implementation

public static IQueryable<table3> GetRows(
EntitiesContext context,
table1 row)
{
var table3Rows =
from t2 in row.table2
join t3 in context.table3 on t2.IdTable3 equals t3.Id
select t3;

return table3Rows;
}


The problem with this approach is that I can't return table3Rows because it's IEnumerable not IQueryable.

Is there any workaround to return IQueryable when using join?

I need IQueryable because I plan to do some other queries against the result.

Answer

You're not going to be able to use the navigation property if you have an already materialized Table1 object. If you have an IQueryable<Table1> then you can use the general approach you're using and the result will just naturally be an IQueryable<Table3>.

Since you have a materialized table row you'll need to query the DB for the Table2 items rather than using the navigation property.

public static IQueryable<table3> GetRows(
  EntitiesContext context, 
  table1 row)
{
  var table3Rows =
    from t2 in context.table2
    where row.Table2Id == t2.Id
    from t3 in t2.Table3 //here we can use a navigation property, since it's not on a materialized object.
    select t3;

  return table3Rows;
}