从一列中选择单个值,从另一个列中选择另一列中的值列表

时间:2017-09-29 05:16:10

标签: sql entity-framework

表1:

productId
productName

表2:

Id
productId - foregn key with references to table 1
productLoacation

我想要选择productId,productName和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()};

如何在不创建实体的情况下在单个查询中实现?

1 个答案:

答案 0 :(得分: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();

另一种方法是使用EntityFramework.Extended库中的Future

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();

这两个查询将在一次数据库之旅中一起执行。

相关问题