LINQ左连接使用Where或语法

时间:2012-04-27 14:53:19

标签: linq linq-to-sql

如何将此存储过程迁移到LINQ

DECLARE @customerIDs TABLE (customerID INT)
DECLARE @c INT

if (@customerName != '')
BEGIN
    INSERT INTO @customerIDs
    select id from customer
    where name like '%' + @customerName + '%'

    SELECT @c = COUNT(*) FROM @customerIDs  
END
else
    SET @c = 0

-- Insert statements for procedure here
SELECT DISTINCT l.*, dbo.GetListOfBranches(l.id) as 'list_of_branches', dbo.GetTopLevelCustomer(cid.customerID) FROM [login] l
LEFT JOIN login_to_customer ltc ON ltc.login_id = l.id
LEFT JOIN @customerIDs cid ON cid.customerID = ltc.customer_id
WHERE 
(@c = 0 OR ltc.customer_id = cid.customerID) AND
(l.surname LIKE '%' + ISNULL(@surname, l.surname) + '%')  AND
(l.forename LIKE '%' + ISNULL(@forename, l.forename) + '%')  AND
 (user_type = ISNULL(@userType, user_type))  AND
 (l.active = ISNULL(@active, l.active)) 
 ORDER BY surname ASC

到目前为止我已经知道了:

List<Int32> customerIds = new List<int>();           
        if (!String.IsNullOrEmpty(customerName))
        {
            CustomerDataContext custDataContext = new CustomerDataContext();

            customerIds = (from a in custDataContext.Customers
                           where a.name.Contains(customerName)
                           select a.id).ToList<Int32>();
        }

        LoginDataContext dataContext = new LoginDataContext();

        var query = (from t in dataContext.logins
                     join t2 in dataContext.login_to_customers on t.id equals t2.login_id into a
                     from subquery in a.DefaultIfEmpty()
                     select new { t, listOfBranches = dataContext.GetListOfBranches(t.id), topLevelCustomer = dataContext.GetTopLevelCustomer(t.id) });

我需要做一个

if (customerIds.Count() > 0)
{
    query = query.Where(a => customerIds.Contains(a.t.customer_id))
}

但是因为我需要执行不同的我不能在查询中有customer_id列。有没有办法包括

LEFT JOIN @customerIDs cid ON cid.customerID = ltc.customer_id
    WHERE 
    (@c = 0 OR ltc.customer_id = cid.customerID)

在LINQ内?

谢谢, 理查德

0 个答案:

没有答案