如何在linq查询C#EF6数据库中首先使用sql server ISJSON函数



我需要从存储在SQL server中的表中检索数据,这个表有json字符串列,然后我需要在C#中使用linq只检索具有有效json列的行,如下所示:

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 
}

如果我理解正确,您只需要在where子句中检查有效的Json字符串。那样的话,我相信你可以做到。

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;
}
}

方法来自此线程:如何使用JSON.NET 确保字符串是有效的JSON

最新更新