Writing objects to the database

The documents that are stored in a schema-less database are often serializations of objects in application code. When working with a relational database, these objects are often stored using an object-relational mapper (ORM), such as Entity Framework, Dapper, or NHibernate. When working with a document database, these objects are often serialized and stored in the database. This means that a change in the definition of that code object will also result in a different document structure when saving the object. Due to the nature of document databases, this will work fine.

As an example, take the following C# class and its JSON representation after serializing it to a document database:

public class Person
{
[JsonConstructor]
private Person() {}

public Person(string name) {
Name = name ?? throw new ArgumentNullException();
}

[JsonProperty]
public string Name { get; private set; }
}
{
“Name”: “Mark Anderson”
}

 

After this code has been running in a production environment for a while, and thousands of persons have been saved, a new requirement comes in. Next to the name of the person, the city where they live must also be recorded. For this reason, the Person class is extended to include another property. After performing this change and deploying the new code, whenever a person is saved, the following code is used, resulting in the JSON shown next to it:

public class Person
{
[JsonConstructor]
private Person() {}

public Person(string name, string city) {
Name = name ?? throw new ArgumentNullException();
City = city ?? throw new ArgumentNullException();
}

[JsonProperty]
public string Name { get; private set; }

[JsonProperty]
public string City { get; private set; }
}
{
“Name”: “Mark Anderson”,
“City”: “Amsterdam”
}

 

While the definition of the Person class has changed—and the corresponding JSON has as well—both document forms can be saved into the same collection.

This shows that from the viewpoint of writing information to the database, the schema-less approach is very convenient, since developers do not have to think about schema change management at all.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.186.164