Ef6点表示法;用类似条件而不是等号连接列
本文关键字:连接 条件 表示 Ef6 | 更新日期: 2023-09-27 18:07:52
我正在尝试连接基于Table2
上的列ID
的两个表,以像列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'
您可以在where
子句中使用交叉连接和StartsWith
来做到这一点:
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);