Primary Keys

Thong Nguyen edited this page Feb 26, 2016 · 2 revisions

Shaolinq supports objects with no primary keys, single primary keys or multiple primary keys. Primary keys can themselves by DataAccessObjects.

Defining an object with no primary key by inheriting from the non-generic DataAccessObject type:

[DataAccessObject]
public abstract class Person
    : DataAccessObject
{
}

Defining an object with one primary key by inheriting from DataAccessObject<T>. The primary key will be inherited from the base DataAcessObject<T> class named Id.

[DataAccessObject]
public abstract class Person
    : DataAccessObject<int>
{
}

Defining an object with one primary key that is not named Id by inheriting from the non-generic DataAccessObject class and manually defining your primary key.

[DataAccessObject]
public abstract class Person
    : DataAccessObject
{
    [PrimaryKey]
    [PersistedMember]
    public abstract T Key { get; set; }
}

Defining an object with multiple primary keys by inheriting from either DataAccessObject and defining two or more primary key properties or by inheriting from DataAccessObject<T> and defining one or more additional primary key properties

[DataAccessObject]
public abstract class Person
    : DataAccessObject
{
    [PrimaryKey]
    [PersistedMember]
    public abstract T Key1 { get; set; }

    [PrimaryKey]
    [PersistedMember]
    public abstract T Key2 { get; set; }
}

You may want to use a base class for all the objects in your model with a convention for naming the primary key column. By default the base DataAcessObject<T> class in Shaolinq names the primary key column Id prefixed by the name of the table. This is declared generically in the DataAccessObject<T> class like follows:

[Serializable]
[DataAccessObject(NotPersisted = true)]
public abstract class DataAccessObject<T>
    : DataAccessObject
    {
        [PrimaryKey]
        [AutoIncrement]
        [PersistedMember(Name = "$(PERSISTED_TYPENAME)$(PROPERTYNAME)", SuffixName = "$(PROPERTYNAME)", PrefixName = "$(PERSISTED_TYPENAME)")]
        public abstract T Id { get; set; }
    }

The PersistedMember attribute has three properties that can be configured. The Name defines the name of the column. When a type(A) is referenced by another type(B), the SuffixName on type-A along with the PrefixName on referencing property of type-B defines the column name of the key on table-B.