2017-09-29 45 views
0

表1的另一列中選擇單個值:從一列和值列表從不同的表

productId 
productName 

表2:

Id 
productId - foregn key with references to table 1 
productLoacation 

我要予以選取的productId,產品名稱和productLoactions的名單?

下面我已經試過了,

var mailAddress = from tb1 in DbContext.table1 
       join tb2 in DbContext.Table2 on tb1.productId equals tb2.productId 
       where tb1.table1== 1234 
       select { tb1.productName, tb2.productLoacation.ToList()}; 

我怎麼能在一個查詢achive而無需創建一個實體?

回答

1

你可以試試這個查詢(我想,那table1字段是唯一標識符):

var mailAddress = (from tb1 in DbContext.table1 
        where tb1.table1 == 1234 
        join tb2 in DbContext.Table2 on tb1.productId equals tb2.productId 
        group tb2 by new { tb1.productId, tb1.productName } into sub 
        select new { 
         sub.Key.productId, 
         sub.Key.productName, 
         productLocations = sub.ToList() 
        }).FirstOrDefault(); 

另一種方法是使用FutureEntityFramework.Extended庫:

var fromTable1Query = DbContext.table1.Where(x => x.table1 == 1234).Future(); 

var fromTable2Query = (from tb1 in DbContext.table1 
         where tb1.table1 == 1234 
         join tb2 in DbContext.table2 on tb1.productId equals tb2.productId 
         select tb2).Future(); 

mailAddress.product = fromTable1Query.ToList().FirstOrDefault(); 
mailAddress.productLocations = fromTable2Query.ToList(); 

這兩個查詢會一起執行一個旅程數據庫。

相關問題