Ninja Database Pro
Creating Indexes
Basic Tasks > Creating Indexes

Primary keys are automatically indexed.  It is possible to create an index on other properties.  Indexes can be either unique or non-unique.  If the index is defined as unique, an exception is throw if a record is attempted to be inserted or updated with an key that already exists.   Composite key indexes can be created by passing in a list of properties.  Perform a IndexExists to determine if an Index already exists for a type.  Index names are case sensitive.  Index queries return index records with a LazyValue.  Index records can be joined together by a LINQ expression.

 

C# Example:

 

NinjaDbPro db = new NinjaDbPro("SingleIndexExampleDir", "SingleIndexExampleDir.db");

db.DeleteEntireDatabase();

 

//Licensed Mode

//db.UserName = "John Smith 101224";

//db.LicenseKey = "aousdf832jasf==";

//Set before OpenDatabase. Default storage is IsolatedStorageDatabase. Other options are:

//db.Storage = new MemoryDatabase(); //In memory database

//db.Storage = new FileDatabase(); //Valid only for non Silverlight projects

 

//Open the database

db.OpenDatabase();

 

//Add a single property index if it doesn't already exist

if (!db.IndexExists<Person>("NameIndex"))

db.AddIndex<Person,string>("NameIndex", "Name", IndexStyle.NonUnique);

 

//Add a record to the database

Person person = new Person();

person.Name = "John Smith";

person.DateCreated = DateTime.Now;

db.Save(person);

 

//Find an exact matach. If the index is unique, this is the fastest.

var exactQuery = db.CreateIndexQuery<Person, string>("NameIndex", "John Smith");

 

//Lazy load the first record and write out a property

Console.WriteLine(exactQuery[0].LazyValue.DateCreated);

 

//Find a partial match

var partialQuery = db.CreateIndexQuery<Person, string>("NameIndex").Where(o => o.Index.StartsWith("John"));

 

//Write the DateCreated for all records that have a name beginning with John

foreach (var indexRecord in partialQuery)

{

Console.WriteLine(indexRecord.LazyValue.DateCreated);

}

 

//Close the database

db.CloseDatabase();