简体   繁体   English

LINQ Join返回IQueryable

[英]LINQ Join returning IQueryable

I've a relationship between 3 tables like this 我在3张桌子之间有这样的关系

在此处输入图片说明

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 我想有一个给定类型的表1和我从表3的所有相关行通过表2的DbContext的参数的方法

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 . 这种方法的问题是我不能返回table3Rows,因为它是IEnumerable而不是IQueryable

Is there any workaround to return IQueryable when using join ? 使用join时是否有任何变通方法可返回IQueryable

I need IQueryable because I plan to do some other queries against the result. 我需要IQueryable,因为我计划针对结果进行其他一些查询。

You're not going to be able to use the navigation property if you have an already materialized Table1 object. 如果您已经实现了Table1对象,则将无法使用navigation属性。 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> . 如果您有IQueryable<Table1>则可以使用所使用的一般方法,结果自然就是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. 由于您有一个物化表行,因此需要在数据库中查询Table2项,而不是使用navigation属性。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM