Skip to content

A simple library that extends Couchbase.Lite to provide extension methods for converting an object to a Document/MutableDocument and a Document/MutableDocument to an object.

License

Notifications You must be signed in to change notification settings

couchbaselabs/Couchbase.Lite.Mapping

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

71 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This is an independent, open source couchbaselabs project, and is NOT officially supported by Couchbase, Inc. Issues are disabled, but if you post a question on the forums you might get an answer.

Couchbase.Lite.Mapping

Couchbase.Lite.Mapping gives developers the ability to dynamically automatically convert generic objects to/from Couchbase Document objects and lists of Result objects. This drastically reduces the amount of, often repeated, code needed to be written to store and retrieve information to and from Couchbase Lite databases.

Table of Contents

  1. Getting Started
  2. Building the Project (optional)
  3. Basic Usage: Object/Document
  4. Basic Usage: IResultSet to Object(s)
  5. Advanced Usage: IResultSet to Object(s)
  6. Customizing Property Name Serialization
    1. Globally
    2. By Document
    3. By Property
  7. Testing

Getting Started

NOTE: As of version 1.0.2, in order to use Couchbase.Lite.Mapping you must have either the Couchbase.Lite or Couchbase.Lite.Enterprise package installed.

Couchbase.Lite.Mapping does not include dependencies so that it can work with both Couchbase.Lite and Couchbase.Lite.Enterprise. This also provides the flexibility to install any compatible version of Couchbase.lite.

Couchbase.Lite.Mapping is available via:

  • NuGet Official Releases: GitHub release

Build (optional)

If you would like to build the package from source instead, follow the steps below

  • Clone the repo
git clone https://github.com/couchbaselabs/Couchbase.Lite.Mapping
  • Build the release version of project using Visual Studio
  • Build the package
cd /path/to/repo/src/Couchbase.Lite.Mapping/packaging/nuget

nuget pack Couchbase.Lite.Mapping.nuspec

Documentation

To get started using Couchbase.Lite or Couchbase.Lite.Enterprise please refer to the official documentation.

Basic Usage: Object/Document

Create a new document with a new object.

// An object to be converted to a document
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

// Create an instance of the object
var person = new Person
{
    FirstName = "Clark",
    LastName = "Kent"
};

// Convert the object into a Couchbase.Lite MutableDocument
var newMutableDocument = person.ToMutableDocument();

// Convert a Couchbase.Lite MutableDocument into an object (of a type specified via generic)
var newPerson = newMutableDocument.ToObject<Person>();

Modify an existing document.

// You can provide the document ID to the ToMutableDocument extension method
// Where "person" is a previously retrieved (and mapped) document, and "id" is a known document ID.
var existingMutableDocument = person.ToMutableDocument($"person::{id}"); 

Note: The ToMutableDocument extension method also

Basic Usage: IResultSet to Object(s)

Default (old) approach

var query = QueryBuilder.Select(SelectResult.All()) 
                                        .From(DataSource.Database(database)) 
                                        .Where(whereQueryExpression); 
                                        
var results = query?.Execute()?.AllResults();

if (results?.Count > 0)
{
    personList = new List<Person>();

    foreach (var result in results)
    {
        // Where 'people' is the containing Dictionary key
        var dictionary = result.GetDictionary("people");

        if (dictionary != null)
        {
            var person = new Person
            {
                FirstName = dictionary.GetString("firstName"), 
                LastName = dictionary.GetString("lastName") 
            };

            personList.Add(person);
        }
    }
}

Couchbase.Lite.Mapping approach

var query = QueryBuilder.Select(SelectResult.All()) 
                                        .From(DataSource.Database(database)) 
                                        .Where(whereQueryExpression); 

var results = query?.Execute()?.AllResults();

// Map all of the results to a list of objects
var personList = results?.ToObjects<Person>(); 

// OR map a single result item to an object
var person = results?[0].ToObject<Person>();

Advanced Usage: IResultSet to Object(s)

You can also map more complex queriies.

Returning Meta ID (and any other valid column)

public class Person
{ 
    public string Type => "person";
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

var query = QueryBuilder.Select(SelectResult.Expression(Meta.ID), SelectResult.All())
            .From(DataSource.Database(Database))
            .Where(Expression.Property("type").EqualTo(Expression.String("person")));

var results = query?.Execute()?.AllResults();

var people = results?.ToObjects<Person>();

Data aggregation

public class PersonStats
{ 
    public int Count { get; set; }
    public string Type { get; set; }
}

var query = QueryBuilder.Select(
                        SelectResult.Expression(Function.Count(Expression.All())).As("count"),
                        SelectResult.Property("type"))
                       .From(DataSource.Database(Database))
                       .Where(Expression.Property("type").NotNullOrMissing())
                       .GroupBy(Expression.Property("type"))
                       .OrderBy(Ordering.Property("type").Ascending());

var results = query?.Execute()?.AllResults();

var personStats = results?[0].ToObjects<PersonStats>(); 

Customizing Property Name Serialization

The default serialization for object property names into Couchbase Lite databases uses Lower Camel Case (e.g. lowerCamelCase).

By default the following object

var person = new Person
{
    FirstName = "Bruce",
    LastName = "Wayne"
};

will look like the following in JSON.

{
    "firstName": "Bruce",
    "lastName": "Wayne"
}

Note the casing of firstName and lastName.

Globally

You can override the default implementation of IPropertyNameConverter by setting Couchbase.Lite.Mapping.Setting.PropertyNameConverter.

using Couchbase.Lite.Mapping;
...

// Set this value to override the default IPropertyNameConverter
Settings.PropertyNameConverter = new CustomPropertyNameConverter();

// Here's an example of a custom implementation of IPropertyNameConverter
public class CustomPropertyNameConverter : IPropertyNameConverter
{
    public string Convert(string propertyName)
    {
      return propertyName.ToUpper();
    }
}

Using CustomerPropertyNameConverter will yield the following JSON seralization for Person.

{
    "FIRSTNAME": "Bruce",
    "LASTNAME": "Wayne"
}

By Document

You can override the default implementation of IPropertyNameConverter at the document level by passing in an instance of a class that implements IPropertyNameConverter into the ToMutableDocument extension method.

var mutableDocument = testObject.ToMutableDocument(new CustomPropertyNameConverter());

By Property

You can override the default implementation of IPropertyNameConverter at the property level by adding a MappingPropertyName attribute above a property.

using Couchbase.Lite.Mapping;

public class Person
{
    [MappingPropertyName("fIRStNaME")]
    public string FirstName { get; set; }

    // This property will be converted using the default converter
    public string LastName { get; set; }
}

Using MappingPropertyName (like above) will yield the following JSON seralization for Person.

{
    "fIRStNaME": "Diana",
    "lastName": "Prince"
}

Testing

Sample App

A sample Xamarin.Forms solution (supporting iOS and Android) can be found within Samples. Simply clone this repo, open Couchbase.Lite.Mapping.Sample.sln, and build/run the application!

The sample app allows users to log in with any username and password, and maintains a user profile per username. Profiles consist of basic information and an image that is persisted as a user profile Document in the Couchbase Lite database for a "logged in" user.

accessibility text

Contributors

Couchbase.Lite.Mapping is an open source project and community contributions are welcome whether they be pull-requests, feedback or filing bug tickets or feature requests.

Please include appropriate unit tests with pull-requests.

We appreciate any contribution no matter how big or small!

Licenses

The mapping package is available under License

Note:: Use of Couchbase.Lite.Mapping has no implications on the Couchbase.Lite.Enterprise or Couchbase.Lite licenses. Those packages are governed by the terms of the Couchbase Enterprise Edition and Community Edition licenses respectively

About

A simple library that extends Couchbase.Lite to provide extension methods for converting an object to a Document/MutableDocument and a Document/MutableDocument to an object.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages