SQLite Attributes and what they do
If like myself, you started using SQLite and just looked up each attribute for the models you're using when and as you needed them, then fine. However you might not realise that the others are there and how they can help you.
Here's a quick summary of the types of attributes available for use (for those of you that don't like reading and just want to know quickly):
-
PrimaryKey This property is the primary key of the table. Only single-column primary keys are supported.
-
AutoIncrement This property is automatically generated by the database upon insert.
-
Indexed This property should have an index created for it.
-
MaxLength If this property is a String then MaxLength is used to specify the varchar max size. The default max length is 140.
-
Ignore This property will not be in the table.
To apply an attribute, simply apply them as below, changing PrimaryKey, AutoIncrement for your chosen attributes.
[PrimaryKey, AutoIncrement] public Int32 ID { get; set; }
So we've found that there are 5 main attributes to work with and how to use them. So what can they be used for?
PrimaryKey
The Primary key is most commonly used alongside AutoIncrement for obvious reasons, this allows you to have a row inserted into your database with an incrementing integer value to which you can reference from another table with the use of a foreign key. Note that the use of PrimaryKey infers that it should also be Indexed, though you do not need to specify this as an index is automatically created for a primary key.
AutoIncrement
Does what it says on the tin, the propertytype should be an integer and should also be marked with the PrimaryKey attribute.
Indexed
Allows your application to quickly lookup a value within the Indexed column.
MaxLength
Limits the available character length for the column.
Ignore
Useful if you've got a large model or information you don't want to store on the device for security purposes or simply a data field that is too complex to fit into a single column.
Bonus attibute: Table
There is another attribute called Table which you can apply to the entire model (class level) that you can use to define table names:
[Table("Members")]
Enjoyed this post, found it useful or have something to add?
Leave a comment below. Also check out this other post about setting up tables in SQLite and making use of the primary key.
Published at 3 Aug 2016, 06:37 AM
Tags: SQLite,Xamarin