0

I need to retrieve data from a table stored in SQL server, this table has json string column, then i need to retrieve only rows with a valid json column using linq in C# like that:

var q = from t1 in DBContext.table1 join  
        t2 in DBContext.table2 on t1.id equals t2.tId
        where 
        //Here what i need to use isJson like that but SqlFunctions does not contain it
        SqlFunctions.IsJson(t1.jsonTxt)
       select new resDTO
        {
          name=t1.name,
          details =t2.details 
        }
        
Asmaa Rashad
  • 593
  • 5
  • 28

1 Answers1

0

If I understand correctly you just want to check for a valid Json string in your where clause. In that case you can do this I believe.

var q = from t1 in DBContext.table1 join  
    t2 in DBContext.table2 on t1.id equals t2.tId
    let isValid = IsValidJson(t1.jsonTxt)
    where isValid == true
   select new resDTO
    {
      name=t1.name,
      details =t2.details 
    }

   private bool IsValidJson(string strInput)
   {
     if (string.IsNullOrWhiteSpace(strInput)) { return false;}
     strInput = strInput.Trim();
     if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
         (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
      {
        try
        {
           var obj = JToken.Parse(strInput);
           return true;
        }
        catch (Exception)
        {
          return false;
        }
      }
     else
      {
       return false;
      }
   }

The method is from this thread: How to make sure that string is valid JSON using JSON.NET

  • I already tried this solution but it gives me this error : `LINQ to Entities does not recognize the method 'Boolean IsValidJson(System.string)' method, and this method cannot be translated into a store expression." RemoteStackIndex: 0` – Asmaa Rashad Apr 14 '22 at 14:41
  • I edited my answer. You can use let to get around the method – Jurgen Volders Apr 15 '22 at 07:09