我正在尝试根据ID
上的Table2
列加入两个表,以便ID
Table1
me.dbSet.Join(me.context.Table2, p => p.ID, e => e.ID,
(p, e) => new { p, e }).Where(z => z.e.ID== uid)
sql输出:
SELECT
1 AS [C1]
FROM [NG].[T1] AS [Extent1]
INNER JOIN [NG].[T2] AS [Extent2] ON [Extent1].[ID] = [Extent2].[ID]
WHERE [Extent2].[ID] = 'f520f7b3-215d-4dfe-9787-1eb6864fb335'
我想用linq编写的sql:
SELECT
1 AS [C1]
FROM [NG].[T1] AS [Extent1]
INNER JOIN [NG].[T2] AS [Extent2] ON [Extent1].[ID] Like [Extent2].[ID] + '%'
WHERE [Extent2].[ID] = 'f520f7b3-215d-4dfe-9787-1eb6864fb335'
答案 0 :(得分:2)
您可以使用StartsWith
子句中的交叉连接和where
执行此操作:
var data = from t1 in Table1
from t2 in Table2
where t1.Id.StartsWith(t2.Id)
&& t2.Id == uid
select new { t1, t2 };
它不会提供您想要的相同SQL,但输出是相同的。
未经测试,但仅使用lambda扩展方法,这应该有效:
var data = me.dbSet
.Join(
me.context.Table2,
p => true,
e => true,
(p, e) => new { p, e })
.Where(z => z.e.ID == uid && z.p.Id.StartsWith(z.e.Id));
另一个可能的选择,如果你知道ID的长度是不变的(它看起来像一个GUID,所以你可能可以依赖它长36个字符:
var data = me.dbSet
.Join(
me.context.Table2,
p => p.Id.Substring(0, 36),
e => e.Id,
(p, e) => new { p, e })
.Where(z => z.e.ID == uid);