【问题标题】:How do I write this cross apply query in LINQ-to-SQL?如何在 LINQ-to-SQL 中编写此交叉应用查询?
【发布时间】:2012-04-04 23:02:46
【问题描述】:

我有以下表格:

create table TableA (
    Id int primary key identity,
    Key int not null
)

create table TableB (
    Id int primary key identity,
    TableA_Id int not null foreign key references TableA(Id),
    Value varchar(80) not null
)

我想使用 lambda 表示法在 LINQ-to-SQL 中编写以下查询:

select TableA.Key, b.Value
from TableA
cross apply (
    select top 10 TableB.Value
    from TableB
    where TableA.Id = TableB.TableA_Id
    order by TableB.Value
) b
where TableA.Key between 0 and 999

我该怎么做?

【问题讨论】:

    标签: linq linq-to-sql


    【解决方案1】:

    这应该可以解决问题

    var query = from a in context.TableA
                from b in context.TableB
                                 .Where(x => x.TableA_Id == a.Id)
                                 .OrderBy(x => x.Value)
                                 .Take(10)
                where a.Key >= 0 && a.Key <= 999
                select new
                {
                  a.Key,
                  b.Value,
                };
    

    【讨论】:

    • 为什么我不能在 b 的 where 条件下使用 a?
    【解决方案2】:

    //获取每个用户的最新活动信息

     var query = ActivityRepository.Where(p => p.iAction > -1 && 
    
       userIds.Contains(p.iSellerId)).GroupBy(c => c.iSellerId).Select(c => c.OrderByDescending(cc => cc.dBeginTime).First()).Select(a => new ActivityInfo
    
            {
                ActivityId = a.iActivityId,
                StartTime = a.dBeginTime,
                SellerId = a.iSellerId,
                EndTime = a.dEndTime,
                ActivityName = a.sName,
            });
    

    此代码将生成外部应用语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-05
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 2013-04-30
      • 1970-01-01
      相关资源
      最近更新 更多