转换SQL查询LINQ

时间:2011-07-14 16:06:20

标签: sql linq

我在将SQL查询转换为LINQ时遇到问题。如何在LINQ where子句中创建case语句?这是我当前的SQL查询,有没有人有任何建议?

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

2 个答案:

答案 0 :(得分:0)

我认为这是某种过滤选项功能吗?

如果是这样,这样的事情应该适用于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);

答案 1 :(得分:0)

在Linq,我会用以下内容构建它:

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);