Linq到实体:无需转换即可连接字符串和整数

时间:2019-04-09 20:31:38

标签: entity-framework

我有2个表:一个表具有一个nvarchar列,其格式如下:“ Type | Id(或GUID)”。如果列的类型是“ Table2”,而第二部分是整数,则table是具有在第一个表中引用的主键。

所以我第一次尝试加入表格是:

    var query = from t1 in db.Table1
            join t2 in db.Table2
                on t1.TypeAndId equals "Table1|" + t2.Id
            select t2;

但这需要永远执行。在分析器中签入查询会生成类似以下内容的

    SELECT 
            [Extent2].[Id] AS [Id]
            FROM  [dbo].[Table1] AS [Extent1]
            INNER JOIN [dbo].[Table2] AS [Extent2] ON [Extent1].[TypeAndId] = (N'Type|' +  CAST( [Extent2].[Id] AS nvarchar(max)))
            WHERE [Extent1].[Id] = @p__linq__0

我们的DBA建议如下:

    SELECT
           [Extent2].[Id] AS [Id]
           FROM  [dbo].[Table1] AS [Extent1]
           INNER JOIN [dbo].[Table2] AS [Extent2] ON replace([Extent1].[TypeAndId],'Type|','') =  [Extent2].[Id]
           WHERE [Extent1].[Id] = 519

因此,显而易见的解决方案是:

    var query = from t1 in db.Table1
            join t2 in db.Table2
                on t1.TypeAndId.Replace("Table1|", "") equals t2.Id
            select t2;

但是,由于一列为nvarchar,另一列为int,因此无法编译。因此,我想知道如何进行联接以生成由数据库管理员建议的查询

0 个答案:

没有答案