Mam problem z konwersją zapytania SQL na LINQ. Jak utworzyć instrukcję case w klauzuli LINQ where? Oto moje aktualne zapytanie SQL, czy ktoś ma jakieś rady?

ALTER PROCEDURE  [dbo].[CustomerBySearch] 

@FirstName VARCHAR(255) = '',
@LastName VARCHAR(255) = '',
@Email VARCHAR(255) = '',
@Phone VARCHAR(30) = ''

AS
BEGIN

SELECT      CustomerId, 
            Title, 
            FirstName, 
            LastName, 
            RegistrationDate, 
            DayPhone, 
            Mobile, 
            LoginEmail 
FROM        CustomerInfo
HAVING      CASE WHEN @FirstName = '' THEN @FirstName ELSE FirstName  END Like @FirstName + '%' 
            AND 
            CASE WHEN @LastName = '' THEN @LastName ELSE LastName  END Like @LastName + '%' 
            AND
            CASE WHEN @Email = '' THEN @Email ELSE LoginEmail  END Like @Email 
            AND
            (
                CASE WHEN @Phone = '' THEN @Phone ELSE DayPhone END LIKE '%' + @Phone
                OR
                CASE WHEN @Phone = '' THEN @Phone ELSE Mobile END LIKE '%' + @Phone
            )
ORDER BY    CustomerId DESC
END
0
Gemini 14 lipiec 2011, 20:06

2 odpowiedzi

Najlepsza odpowiedź

Rozumiem, że jest to jakaś funkcja opcji filtrowania?

Jeśli tak, coś takiego powinno działać z linq...

var infos = customerInfos;

if(!string.IsNullOfEmpty(firstname))
   infos = infos.Where(i => i.FirstName.Contains(firstname));
if(!string.IsNullOfEmpty(lastname))
   infos = infos.Where(i => i.LastName.Contains(lastname));
if(!string.IsNullOfEmpty(email))
   infos = infos.Where(i => i.Email.Contains(email));
if(!string.IsNullOfEmpty(phone))
   infos = infos.Where(i => i.DayPhone.Contains(phone) || i.Mobile.Contains(phone));

infos = infos.OrderByDescending(i => i.CustomerId);
0
musefan 14 lipiec 2011, 20:13

W Linq zbudowałbym to, używając czegoś takiego:

var query = db.CustomerInfo;

if (!string.IsNullOrEqual(firstName)) 
   query = query.Where(x => x.FirstName.StartsWith(firstName));

// similar if statements for lastname, email and phone, each one building on the existing query

return query.OrderBy(x => x.CustomerId);
0
Stuart 14 lipiec 2011, 20:13