0

Json string is updated to one of the columns of SQL Server, I want the rows that matches my condition and store it to a collection. In this case, I am applying the condition to the json key/ name in order to fetch the data. I achieved it in entity framework with the help of sqlquery function. But I trying to find other options that we have for same circumstance maybe linq or lambda.

Example it is a movie table that has 3 columns among which Movie_info column is a NVarChar that contains Json string.

 id: 1
 Storyline: "Blah Blah!!"
 Movie_info [{"title":"The Shawshank Redemption","year":1994,"cast":["Morgan 
 Freeman", "Tim Robbins"]}]`

 id: 2
 Storyline: "free from corruption."
 Movie_info [{"title":"Batman Begins","year":2005,"cast":[],"Director": 
 "Christopher Nolan"}]
 .
 ..
 ...

I am trying to filter the movies that were released in the year 2005. Below is the code I tried and it worked successfully.

using (MoviesDbContext ctx = new MoviesDbContext())
{
    var movieList = ctx.Movies.SqlQuery("SELECT * FROM [Movie].[dbo].[Movies] 
                                         WHERE JSON_VALUE(Movie_info, '$.year') = @value", 
                                        new SqlParameter("@value", 2005)).ToList();
}

With this code I got list of Movies that were released in the year 2005. How can I achieve the same using Lambda or using Linq queries because I don't want to hardcode SQL statements to the controller..

I am expecting the same result. suggestion on any other approach is much appreciated..

2 Answers 2

1

from visualstudiomagazine.com There is, as yet, no support in Entity Framework or LINQ to leverage the TSQL JSON functionality.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you Nabi, do you have suggestion how to avoid hardcoding the sql queries to the code?
You can take advantage of nameof() operator or reflection, but I personally prefer move raw queries to resource files, so that I can manipulate them easily. Having the queries in a separate library could be of great help too.
After some research I come to know that stored procedure is one way out of this situation as Reflections in C# are not that efficient. What is your opinion about this?
It depends on your situation. For example, are the store procedures under source controller? This link may be useful. stackoverflow.com/questions/15142/…
0

You could use Reflectionsto get the Propertyname of the requested JSON item to put it in the Query, but be aware that reflections are slow. for further information see https://www.tutorialspoint.com/csharp/csharp_reflection.htm

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.