niedziela, 1 kwietnia 2012

EXIST w LINQ

Niedawno szukałem w jaki sposób generować za pomocą LINQ klauzulę EXIST.
Otóż istnieje prosty wzorzec na generowanie tej klauzuli:


Code:
            using (var context = new AdventureWorksLT2008R2Entities())
            {
                var q = from p in context.Product
                        where context.Product.Any(x => x.ListPrice > 1490)
                        select p;
                var sql = ((ObjectQuery) q).ToTraceString();
            }

Kluczem jest tutaj metoda Any. Właśnie ta metoda tworzy klauzulę EXIST, jeżeli chcemy uzyskać NOT EXIST wystarczy zaprzeczyć.

Wygenerowany SQL ma następującą postać:

SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[Name] AS [Name],
[Extent1].[ProductNumber] AS [ProductNumber],
[Extent1].[Color] AS [Color],
[Extent1].[StandardCost] AS [StandardCost],
[Extent1].[ListPrice] AS [ListPrice],
[Extent1].[Size] AS [Size],
[Extent1].[Weight] AS [Weight],
[Extent1].[ProductCategoryID] AS [ProductCategoryID],
[Extent1].[ProductModelID] AS [ProductModelID],
[Extent1].[SellStartDate] AS [SellStartDate],
[Extent1].[SellEndDate] AS [SellEndDate],
[Extent1].[DiscontinuedDate] AS [DiscontinuedDate],
[Extent1].[ThumbNailPhoto] AS [ThumbNailPhoto],
[Extent1].[ThumbnailPhotoFileName] AS [ThumbnailPhotoFileName],
[Extent1].[rowguid] AS [rowguid],
[Extent1].[ModifiedDate] AS [ModifiedDate]
FROM [SalesLT].[Product] AS [Extent1]
WHERE  EXISTS (SELECT
    1 AS [C1]
    FROM [SalesLT].[Product] AS [Extent2]
    WHERE [Extent2].[ListPrice] > cast(1490 as decimal(18))
)

Brak komentarzy:

Prześlij komentarz