Skip to content

Making a data class persistent

CPU edited this page Feb 14, 2022 · 2 revisions

If a part of the code requires some data to to be stored, you can use the persistence framework developed for the bot. It is enough that you define your class in this way:

public class MyPersistentClass : Entity {
  [Key]
  public ulong id;
  [NotNull]
  [Index]
  public string name;
  public float number;
}

The class can be transformed to a table by using the command: Database.AddTable<MyPersistentClass>(); No other code is required. If the table is missing, it will be created, if not just the entity behind the scenes will be created. New columns can be added to an existing class without losing data.

You can access the persistence with the commands:

  • Database.Count<T>() will return the number of objects for the specified entity
  • Database.Add<T>(T val) adds or updates an entry in the database (aliases: Update<T>(T val) adn Insert<T>(T val) they all work the same)
  • Delete<T>(T val) deletes an entry from the DB
  • DeleteByKeys<T>(object[] keyvalues) deletes an entry from the DB specifying the value of the keys to identify the object
  • T = Database.Get<T>(object keyvalue) gets an instance of the class from the DB using the value of the key. Returns null if the key is not present
  • List<T> = Database.GetAll<T>() returns a list of all entries in the database for the specified Entity

The attribute types mapped are: int8, uint8, byte, int, int32, int64, long, uint64, ulong, string, bool, DateTime, float, double, and byte[]

The attribute tag to be sued are:

  • Key the attribute will be handled as primary key. At least one attribute has to have this tag. Multiple key columns are possible. All them together will constitute the key for the table
  • NotNull the attribute will not allow null values
  • Index all the attributes with this tag will construct a single index for the table
  • Comment the string attribute will be optimized to contain long text
  • Blob the attribute is handled as byte array
  • NotPersistent the attribute is ignored and will not be made persistent (same as having private attributes)
Clone this wiki locally