将存储过程转换为LINQ到实体

时间:2011-11-21 10:57:20

标签: c# .net linq entity-framework-4 linq-to-entities

请参阅底部的编辑,了解我的问题的当前状态。

我正在将存储过程转换为LINQ to Entities并且正在取得一些进展。但是我正在踩到以下几点:

在SP的WHERE子句中,传入的空值按以下方式处理:

WHERE (@customerId IS NULL OR (CUST.CustomerID = @customerId))

到目前为止,我已经提出以下建议:

return entities.Contacts
    .Include("Individuals")                
    .Where(c => customerId.HasValue && c.Individuals.Any(i => i.CustomerID == customerId.Value))
    .Select(c => c)
    .OrderBy(o => o.LastName)
    .Take(10)
    .ToList(); 

这根本不起作用。返回0项。任何人都可以建议如何将其转换为LINQ语法。谢谢!

修改 我几乎得到了这个。现在唯一美中不足的是订购。由于某种原因,订购不受尊重。这是一些代码:

public static List<Contact> GetAllTheCusts(string fName,
        string lName,
        string middleName,
        int? customerId, 
        string sort, 
        int pageIndex, 
        int pageSize)
    {
        AWEntities entities = Common.GetContext();

        int skipCount = pageSize * pageIndex;

        var contacts = entities.Contacts
            .Include("Individuals.Customer")
            .Where(c => customerId.HasValue
                            ? c.Individuals.Any(i => i.CustomerID == customerId.Value)
                            : c.Individuals.Any(i => i.Customer.CustomerID == i.CustomerID))
            .Where(c => string.IsNullOrEmpty(fName) || c.FirstName.Contains(fName))
            .Where(c => string.IsNullOrEmpty(lName) || c.LastName.Contains(lName))
            .Where(c => string.IsNullOrEmpty(middleName) || c.MiddleName.Contains(middleName));
            .Select(c => c);

        IOrderedQueryable<Contact> contactsOrdered = contacts.OrderByDescending(o => o.ContactID);;

        return contactsOrdered.Skip(skipCount).Take(pageSize).ToList();

    }

我很高兴看到订单得到解决。 感谢

3 个答案:

答案 0 :(得分:3)

仅当customerId非空

时才过滤
var contacts = entities.Contacts;

if (customerId != null)
{
   contacts = contacts.Where(c => c.Individuals.Any(i => i.CustomerID == customerId.Value));
}

return contacts
    .OrderBy(o => o.LastName)
    .Take(10)
    .ToList(); 

答案 1 :(得分:0)

以下工作会怎样?

Where(c => !customerId.HasValue || (customerId.HasValue && c.Individuals.Any(i => i.CustomerID == customerId.Value)))

答案 2 :(得分:0)

看起来你在where子句中意外使用了&&,而你的意思是||