简体   繁体   中英

C# stored procedure with json path

I try to work with json in SQL Server. I've create a stored procedure:

CREATE PROC [Production].[pr_GetForSearchAutocomplete]
WITH ENCRYPTION
AS
BEGIN
    SELECT [Code] AS 'Name'
        ,b.[Name] AS 'Brand'
    FROM [Production].[Products] p
    INNER JOIN [Production].[Brands] b on p.[BrandID] = b.[BrandID] 
    UNION
    SELECT oe.[Name] AS 'Name'
        ,ob.[Name] AS 'Brand' 
    FROM [Production].[OriginalElements] oe
    INNER JOIN [Production].[OeBrands] ob on ob.[OeBrandID] = oe.[OeBrandID]
    FOR JSON PATH
END
GO

Now, I try to call it in Entiry Framework. Function import in entity model return only colletions. So< I try to use SqlQuery:

public async Task<string> GetForSearchAutocomplete()
{
    string query = "EXEC [Production].[pr_GetForSearchAutocomplete]";
    var result =string.Concat(_context.Database.SqlQuery<string>(query));
    return result;
}

And in Web API I try to use it like this.

public async Task<IHttpActionResult> GetForSearchAutocomplete()
{
    using (var unitOfWork = Factory.Create())
    {
        var result = await unitOfWork.GetForSearchAutocomplete();
        return Json(result);
    }
}

The result I got is:

"[{\"Name\":\"11111111111001\",\"Brand\":\"888\"},{\"Name\":\"\\\"YO\\\"\",\"Brand\":\"FLEETGUARD\"},{\"Name\":\"11111111111002\",\"Brand\":\"FLEETGUARD\"}
…]"

But it is a string, not json array, because GetForSearchAutocomplete() return string as I think.

And now I have to create class and deserialize this string to json array in Web API. But I don't see any difference bettwen this, and return a list from stored procedure and use Json(myList) in Web API.

So, is there any another way to use stored procedures with json in C#?

You need to deserialize that JSON obtain. Use:

JsonConvert.DeserializeObject<string>(result)

You should convert the string returned by SQL to an object before returning it in the API result.

var result = await unitOfWork.GetForSearchAutocomplete();

var obj = JsonConvert.DeserializeObject(result);
// or
// var obj = JsonConvert.DeserializeObject<Array<T>>(result)

return Json(obj);

As an alternative to deserializing the object only to serialize it again in the Json method, you could do the following:

var result = await unitOfWork.GetForSearchAutocomplete();
return Content(result, "application/json");

The reason for this is that the SQL is returning a string of the JSON. The Json() method converts a C# object into a JSON string. If you pass a JSON string into a JSON converter, the browser/parser will interpret that as the original JSON string, not the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM