C#, Realm

using enums with Realm

Realm is a very sweet object-oriented database engine for various languages. Since I am a .Net developer, I’ll stick to the features and problems we have using it within Xamarin Apps.

Recently we encountered a problem, using enums within a RealmObject. The most challenging thing in using Realm is, the constraint that comes with the Realm Models, they can not inherit each other, and Properties may only be a hand full of types or other RealmObjects (see: Realm: Supported Types). For a complete reference to Realm, feel free to stick to the .Net Tutorial on realm.io, it’s pretty neat.

So, as you can imagine from the headline, there is no out-of-the-box support for enums, but it’s pretty easy to achieve a proper solution.

Let’s assume we have Model with some enums:

public class Transaction : RealmObject
{
[PrimaryKey]
public int TransactionId { get; set; }
// this will not compile
public TransactionState State { get; set; }
public string Subject { get; set; }
public double Amount { get; set; }
}
public enum TransactionState
{
Open,
Comitted,
InTransaction,
Aborted,
Failed
}

The problem with this code snippet is, that enums are not supported in Realm, so the compiler (actually Fody) will give us an error, stating it is not a supported type:

Error Fody/Realm: Transaction.State is an ‘AsyncViewModel.Models.TransactionState‘ which is not yet supported. Models\Transaction.cs 12

How to solve this problem? Enums are always backed by another type, usually, it is an int (one can specify other types, but this is normally not the case). How about saving the int to Realm? But we want to keep the actual enum within the model, so we use a pseudo property (since Realm can only save auto-properties, no fields).

public TransactionState State
{
get { return (TransactionState)StateId; }
set { StateId = (int)value; }
}
public int StateId { get; set; }

So that’s it. We could also add an [Ignored] Attribute to the State property, but Fody is automatically ignoring non-auto properties.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.