使用LINQ进行内联选择

时间:2009-12-15 01:04:30

标签: linq tsql linq-to-entities

我需要使用LINQ:

复制具有内部选择的T-SQL语句
SELECT *, 
CustomerTypes.Description as CustomerType, 
(Select Min(Distinct DocumentStatistics.StatDateTime) As LastStatCheck
From DocumentStatistics
Where DocumentStatistics.CustomerId = Customers.CustomerId) As LastStatCheck 
FROM Customers 
INNER JOIN CustomerTypes ON Customers.CustomerTypeID = CustomerTypes.CustomerTypeID 
ORDER BY CustomerName

以下是我能够来的最接近的,但它最终会返回所有的DocumentStatistics,40,000 plus。

            Dim docQuery = (From doc In data.DocumentStatistics _
                       Select doc)

        Dim query = From customer In data.Customers _
                    Join docStat In docQuery _
                    On customer.CustomerID Equals docStat.CustomerID _
                    Select Customer = customer, LastStatCheck = _
                        (From doc In docQuery Where customer.CustomerID = doc.CustomerID _
                        Select doc.StatDateTime).Distinct().Min()

我错过了什么?我如何复制初始SQL语句?

我可以使用VB或C#示例,我正在使用SQL Server数据库。

4 个答案:

答案 0 :(得分:3)

您需要使用Group Join功能来实现此功能,如C#中的以下内容:

var result = from customer in data.Customers
             join docStat in data.DocumentStatistics
                    on customer.CustomerID equals docStat.CustomerID into stats
             where stats.Count() > 0
             select new
             {
                 Customer = customer,
                 LastStatCheck = stats.Min(res => res.StatDateTime)
             };

并在VB.Net中

Dim result = From customer In data.Customers _
             Group Join docStat In data.DocumentStatistics _
                  On customer.CustomerID Equals docStat.CustomerID Into stats = Group _
             Where stats.Count() > 0 _
             Select New With _
             { _
                 .Customer = customer _
                 .LastStatCheck = stats.Min(Function(res) res.StatDateTime) _
             }

答案 1 :(得分:1)

约翰,

查看名为Linqer的产品(我与此产品无关)。它需要一个SQL语句并将其转换为LINQ。它几乎可以转换你抛出的任何查询。这对我来说非常有用。它也教会了我很多关于LINQ的工作原理。

兰迪

答案 2 :(得分:1)

你真正想要的是团体加入。

C#示例:

var query = from c in data.Customers
            join ds in data.DocumentStatistics
            on c.CustomerID equals ds.CustomerID into stats
            select new
            {
                Customer = c,
                LastStatCheck = stats.Min(s => s.StatDateTime)
            };

答案 3 :(得分:0)

Linqer从我原来的SQL语句中给了我以下结果:

From customer In data.Customers _
                    Select _
                    Customer = customer, _
                    LastStatCheck = (CType((Aggregate lastDateChecked In _
                    (From docStat In data.DocumentStatistics _
                    Where docStat.CustomerID = customer.CustomerID _
                    Select docStat) Into Min(lastDateChecked.StatDateTime)), DateTime?))

关于Linqer的有用之处在于我可以将t-SQL语句放在LINQ语句旁边并运行查询。