我有以下命令:
var query = from x in context.FirstTable.Include("SecondTable")
where x.TestColumn == 5 &&
x.SecondTable.SecondTestColumn == 3
select x;
现在我还想从名为“ThirdTable”的第三个表中加载条目。 但我只能通过SecondTable表引用它。从FirstTable到SecondTable有一个外键,从SecondTable到ThirdTable有一个外键,但从FirstTable到ThirdTable都没有。
使用以下查询是不可能的。例外情况是它无法从FirstTable导航到ThirdTable:
var query = from x in context.FirstTable.Include("SecondTable").Include("ThirdTable")
where x.TestColumn == 5 &&
x.SecondTable.SecondTestColumn == 3
select x;
或者我是否需要对从该查询中返回的每个结果集对ThirdTable进行额外的查询?
非常感谢你!
Craig Stuntz:
我有以下外键:table1< - > table2< - >表3
让我们说这些表格如下:订单< - >客户< - > customer_preferences
所以我没有必要从订单到customer_preferences制作外键 大部分时间都没有必要。这次我想保护一些额外的数据库往返。
答案 0 :(得分:2)
您可以通过预先加载来完成此操作:
var query = from x in context.FirstTable.Include("SecondTable.ThirdTable") // remember, these are property names, not table names
where x.TestColumn == 5
&& x.SecondTable.SecondTestColumn == 3
select x;
或者(这是我使用的方法,主要是)投影:
var query = from x in context.FirstTable
where x.TestColumn == 5
&& x.SecondTable.SecondTestColumn == 3
select new PresentationModel
{
FirstTableColumn = x.Something,
SecondTableColumn = x.SecondTable.SomethingElse,
ThirdTableColumn = x.SecondTable.ThirdTable.StillMore
};
这假设SecondTable:ThirdTable是1:1(你不说)。如果它是1:*,你会做类似的事情:
var query = from x in context.FirstTable
where x.TestColumn == 5
&& x.SecondTable.SecondTestColumn == 3
select new PresentationModel
{
FirstTableColumn = x.Something,
SecondTableColumn = x.SecondTable.SomethingElse,
ThirdTableStuff = from y in x.SecondTable.ThirdTable
select y.StillMore
};
答案 1 :(得分:1)
如果我没记错的话,Include仅适用于第一个表格。你可以这样做:
var query = from x in Invoices
join p in Products
on x.Invoice_id equals p.Invoice_id
join c in Customers
on x.Customer_id equals c.Customer_id
where p.Customer_id == 123
&& c.Description == "some description"
select x;
您也可以尝试这样的事情
var query = from x in context.FirstTable.Include("SecondTable").Include("SecondTable.ThirdTable")
where x.TestColumn == 5 &&
x.SecondTable.SecondTestColumn == 3
select x;