简体   繁体   English

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

[英]Select single value from one column and list of values from another column from different table

Table 1: 表格1:

productId
productName

Table 2: 表2:

Id
productId - foregn key with references to table 1
productLoacation

I want toselect productId,productName and list of productLoactions? 我要选择productId,productName和productLoactions列表吗?

I have tried as below, 我已经尝试过如下

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

How can I achive in a single query without creating a entity? 如何在不创建实体的情况下实现单个查询?

You can try this query (I suppose, that table1 field is unique identifier): 您可以尝试以下查询(我想, 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();

Another way is to use Future from EntityFramework.Extended library: 另一种方法是使用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();

These two queries will be executed together in exactly one trip to database. 这两个查询将一起在只有一个旅行数据库中执行。

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

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