简体   繁体   中英

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

Table 1:

productId
productName

Table 2:

Id
productId - foregn key with references to table 1
productLoacation

I want toselect productId,productName and list of 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):

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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