I considering to store some information as a JSON object in a SQL Server database but it is not clear for me how I should update a single property of that object in JSON column but not the whole object.
It is an asp.net core application. As ORM I use Entity Framework core. I want to create a class which will look like this example:
public class Person{
public int Id {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public string AdditionData {get;set;} //json object
}
And JSON object in "AdditionData" column will have the following format:
{
phoneNumbers:["123456789","789456123"],
groups:[{name:"g1", description:"blah"}, {name:"g2", description:"blah2"}]
}
So now I want add new PhoneNumber to some person and method signature might look like this:
void AddPhoneNumber(int personId, string phoneNumber);
I found only two options how I can add new phoneNumber to described object.
First option:
- find person by id using EF
- deserialize whole AdditionData object from string
- add new phoneNumber to additionData.PhoneNumbers list
- serialize AdditionData object back to string
- update person.AdditionData property with this string
- perform "saveChanges"
Second option:
Use JSON_MODIFY
SQL function and execute raw SQL with parameter, something like this:
context.Database.ExecuteSqlCommand("UPDATE Person
SET additionalData = JSON_MODIFY(additionalData,"append $.phoneNumbers", @phoneNumber)
WHERE Id= @personId", personIdParam,phoneNumberParam);
The Question: Is there another way to do this? Because those two ways, which I described, don't look elegant to me (especially first one).