Ef6点符号;加入colums就像条件一样,不等于

时间:2015-08-14 11:11:43

标签: c# .net entity-framework entity-framework-6

我正在尝试根据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'

1 个答案:

答案 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);