Saturday, June 1, 2013

Seeding a Lex.DB

Lex.DB is an object database that can be used in Windows Store and Windows Phone apps.   This is a fast free alternative to SQLite.

To learn more about Lex.DB see Lex's blog



In my case I wanted to include a database that already had data in it with a windows phone 8 app I created.


List<AutoMobileInformation.AutoMobileCodes> lstComplete = 
                        new List<AutoMobileInformation.AutoMobileCodes>();
using (var db = new DbInstance("auto codes"))
{
     db.Map<AutoMobileInformation.AutoMobileCodes>().Automap(i => i.Id)
                       .WithIndex("Code", i => i.Code).WithIndex("Manufacture", i => i.Manufacture);
     db.Initialize();
     lstComplete = db.LoadAll<AutoMobileInformation.AutoMobileCodes>().ToList();
     if (lstComplete.Count == 0)
    {
         var lex = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Lex.Db"
                         CreationCollisionOption.OpenIfExists);
         var auto = await lex.CreateFolderAsync("auto codes"
                         CreationCollisionOption.OpenIfExists);
         StorageFile seedFile1 = await StorageFile.GetFileFromPathAsync(
                     Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, 
                                  @"AutoMobileCodes.index"));
         StorageFile seedFile2 = await StorageFile.GetFileFromPathAsync(
                     Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, 
                                  @"AutoMobileCodes.data"));
         await seedFile1.CopyAsync(auto, @"AutoMobileCodes.index"
                     NameCollisionOption.ReplaceExisting);
         await seedFile2.CopyAsync(auto, @"AutoMobileCodes.data"
                     NameCollisionOption.ReplaceExisting);
    }
}
In the code first we create an instance of the database.  The we add an index to the database.  Then we check and see if there is any data in the database.  
If there is not I replace the Index and Data file in isolated storage with files that have data.