LINQ:如何使用组加入的数据加入子表?

时间:2018-04-12 17:07:57

标签: vb.net linq

我必须在我正在处理的其中一个应用程序中扩展现有查询。

表关系如下:

tableName     relationship   tableName2     Join columns 
title         1:1            parcel         p_id:p_id   
title         1:many      transaction    title_no:new_title_no  
transactions  many:1         title          old_title_no:title_no

查询本质上是一个数据加载器,用于减少到数据库的往返次数 现有查询如下所示:

From title In context.Title
Join parcel In context.Parcel 
On title.p_id Equals parcel.P_Id
Group Join transaction In context.Transaction
On title.title_no Equals transaction.New_Title_No And title.transfer_date Equals transaction.Transfer_Date Into transactions = Group 
Select New TitleSearchResult() With {.Title = title, .Pc_Parcel = parcel, .Transactions = transactions}

返回自定义数据类型以存储不同的值。

应用程序还映射这些值(Title实体包含未映射的属性以存储来自其他实体的数据):

 For Each result In query
      result.Title.Parcel = result.Parcel
      result.Title.Transactions = result.Transactions.ToList()
 Next

我需要根据old_title_no返回与每笔交易相关的标题 我试图按如下方式解决查询:

Dim query1 = From title In context.Title
             Join parcel In context.Parcel 
             On title.p_id Equals parcel.P_Id
             Select title, parcel
Dim query2 = From title_old In context.Title
             Join trans As Transaction In context.Transaction 
             On title_old.title_no Equals trans.Old_Title_No
             Select trans, title_old
Dim query3 = From b In query1
             Group Join c In query2
             On b.title.title_no Equals c.trans.New_Title_No And b.title.transfer_date Equals c.trans.Transfer_Date
             Into transactions = Group
             Select b.title, b.parcel, transactions

这似乎做了正确的查询,但是不允许我创建一个新的TitleSearchResult对象,如下所示(因为我无法从事务对象中分解数据):

From t In query3.ToList()
Select New TitleSearchResult() With {.Title = t.title, .Pc_Parcel = t.parcel, _
.Transactions = t.transactions.trans, .Old_Titles = t.transactions.title_old}

我怎样才能在事务上进行组连接(因为我需要返回IEnumerable以便我可以在数据库的另一个查询中使用它)并且能够分离trans和title_old对象?

1 个答案:

答案 0 :(得分:1)

假设TitleSearchResult ListOld_TitlesTransactions种类型,您可以这样做:

var ans =  From t In query3.ToList() _
           Select New TitleSearchResult() With {
               .Title = t.title,
               .Pc_Parcel = t.parcel,
               .Transactions = t.transactions.Select(Function(t1) t1.trans).ToList(),
               .Old_Titles = t.transactions.Select(Function(t1) t1.title_old).ToList()
           }