【发布时间】:2015-11-24 08:23:19
【问题描述】:
我有三张桌子。
*Contract*
ContractID(PK)
AgentID(FK)
CustomerID(FK)
Status
*Agent*
AgentID
Name
*Customer*
CustomerID
Name
我需要编写一个查询来选择代理名称包含“abc”且客户名称包含“xyz”的所有合同。
我的 Linq 查询是:
from c in ctx.Contracts
from a in ctx.Agents
from cu in ctx.Customers
where c.CustomerID == cu.CustomerID && c.AgentID == a.AgentID &&
a.Name.Contains("abc") && cu.Name.Contains("xyz")
select c
生成的SQL是:
SELECT
[Filter1].[ContractID] AS [ContractID],
[Filter1].[AgentID1] AS [AgentID],
[Filter1].[Status] AS [Status],
[Filter1].[CustomerID] AS [CustomerID]
FROM (SELECT
[Extent1].[ContractID] AS [ContractID],
[Extent1].[AgentID] AS [AgentID1],
[Extent1].[Status] AS [Status],
[Extent1].[CustomerID] AS [CustomerID]
FROM [dbo].[Contract] AS [Extent1]
INNER JOIN [dbo].[Agent] AS [Extent2] ON [Extent1].[AgentID] =
[Extent2].[AgentID]
WHERE [Extent2].[FirstName] LIKE N'%abc%' ) AS [Filter1]
INNER JOIN [dbo].[Customer] AS [Extent3] ON [Filter1].[CustomerID] =
[Extent3].[CustomerID]
WHERE [Extent3].[FirstName] LIKE N'%xyz%'
我正在努力用 Lambda 表达式编写它。任何帮助将不胜感激。
以及如何使用“OR”编写相同的查询。
from c in ctx.Contracts
from a in ctx.Agents
from cu in ctx.Customers
where c.CustomerID == cu.CustomerID && c.AgentID == a.AgentID &&
a.Name.Contains("abc") || cu.Name.Contains("xyz")
select c
【问题讨论】:
标签: sql linq lambda inner-join