具有XPath查询的SQL到LINQ转换

时间:2018-03-05 16:54:28

标签: c# linq tsql xpath linq-to-sql

我开始从存储过程中删除一些SQL代码并将其转换为LINQ以在我的C#.NET应用程序中使用。使用下面的示例,如果xpath在XML列数据中找到匹配项,则查询应返回true。我是LINQ的新手,所以转换这个查询一直很有挑战性。任何帮助,将不胜感激! \ m / \ m /

declare
@userID       as uniqueidentifier = '8D1FA128-1684-487F-B7B2-978CE7FC6C83',
@isRockNRoll  as bit;

select @isRockNRoll = CASE WHEN EXISTS(select 1 from dbo.[MyTableName] where [myTableColumnName].query('/descendant-or-self::node()/text').value('text[1]/@userID','varchar(40)') = CONVERT(varchar(40),@userID)
                      and [myTableColumnName].query('/descendant-or-self::node()/text').value('text[1]/@genre','varchar(50)') = 'RockNRoll') THEN 1
                      ELSE 0 END

-- myTableColumnName XML column value:
-- <userID>8D1FA128-1684-487F-B7B2-978CE7FC6C83</userID><genre>RockNRoll</genre>

.NET实现示例。

    private bool IsRockNRoll(Guid userID)
    {
        using (var context = new MyContext())
        {
            var strIsRockNRoll = (from TBL in context.MyTableName
                                  where TBL.myTableColumnName.userID == userID
                                  && TBL.myTableColumnName.genre == "RockNRoll").SingleOrDefault();

            if (strIsRockNRoll != null)
            {
                    return true;
            }
            else
            {
                return false;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我是LINQ的新手,但这似乎有用...... \ m / \ m /

private bool IsRockNRoll(Guid userID)
{
    using (var context = new MyContext())
    {
        bool blnIsRockNRoll = false;
        var result = (from o in context.MyTableName.AsEnumerable()
                        where o.myTableColumnName.Contains(userID.ToString())
                        && o.myTableColumnName.Contains("RockNRoll")
                        select o).ToList();

        if (result.Count > 0)
        {
            blnIsRockNRoll = true;
        }

        return blnIsRockNRoll;
    }
}