2

我需要将查询从 sql 转换为 linq 创建表历史

CREATE TABLE [dbo].[History](
    [HistoryID] [int] IDENTITY(1,1) NOT NULL,
    [AuctionID] [int] NOT NULL,
    [UserName] [nvarchar](128) NULL,
    [Time] [datetime] NOT NULL,
    [Price] [decimal](18, 2) NOT NULL,
)

询问

select [UserName],[Price] from [History] 
where [Price] in 
    (SELECT [Price] FROM [History]  
    where ID=28 GROUP BY [Price]
    HAVING COUNT(*)=1) 
        Order by [Price]
4

2 回答 2

2

我认为您正在寻找LINQ类似于您的 SP 的声明。使用以下一种

// Using Plain LINQ statements
var result1 = from history in lstHistory
              where history.ID == 28
              group history by history.Price into g
              orderby g.Key
              where g.Count() == 1
              select new 
                { 
                    Price = g.Key, 
                    UserName = g.Select(h => h.UserName).FirstOrDefault() 
                };

或者

// Using Lambda Expressions
var result2 = lstHistory
                .Where(q => q.ID == 28)
                .OrderBy(t => t.Price)
                .GroupBy(h => h.Price)
                .Where(grp => grp.Count() == 1)
                .Select(g => new 
                           { 
                              Price = g.Key, 
                              UserName = g.Select(h => h.UserName).FirstOrDefault() 
                            });
于 2012-11-05T19:17:29.277 回答
0

我想你正在寻找这个

var query = from h in context.History
            where 
              (from h2 in context.History
               h2.ID == 28
               group h2 by h2.Price into g
               where g.Count() == 1
               select g.Key).Any(x => x == h.Price)
            orderby h.Price
            select new {
              h.UserName,
              h.Price
            };
于 2012-11-05T18:44:30.843 回答