Mango- Baby Steps: Creating an application with a local Database
I was working lately on a new app , ToDo list ( i know , nothing innovative here -_- ) but then I dropped the work till Mango is out,for the very good reason that with Mango I can have a local Database to store and manage my application’s structured data ! Clap ! Clap!
One of the new many features coming with the Windows Phone Codenamed Mango is the possibility of having local databases- Microsoft SQL Server Compact edition databases(SQL CE)- for your applications.
The database resides in the application’s isolated storageas a file.
In case you are not familiar with the isolated storage,I highly recommend you to read the ” All about WP7 Isolated Storage” articles on the ” WindowsPhone Geek” website.
In order to store and retrieve data in the local database, your Windows Phone application has to use LINQ to SQL.
” LINQ to SQL provides an object-oriented approach to working with data and comprises an object model and a runtime.The LINQ to SQL object model is made up primarily by the System.Data.Linq.DataContext object, which acts as a proxy for the local database. The LINQ to SQL runtime is responsible for bridging the world of objects (the DataContext object) with the world of data (the local database). This relationship is summarized in the following image.” MSDN
One more thing to explain is the Data Context . Data Context is the object model that represents the database, each object is a set of entities using the ” plain old CLR object ” (POCO) with attributes.
- Building the application
My ToDo application looks like this :
As you can see, my main page is a panorama containing :
* Hot list item : where you can find the tasks to be done soon
* Lists: tasks will be sorted , tasks related to work, family, etc…
The other page is a simple Windows Phone page that allows you to add a new task.
In this post we will be working with this user interface.By now you should know how to create a new Windows Phone 7.1 application and how to add pages, so all I have to do is to show you the XAML code :
Now that the user interface is ready, we will build the Data Context.
First thing to do is to add the reference System.Data.Linq to be able to work with LINQ to SQL.
Then add a new class, I’ll call it task .
Add another class called TaskDataContext that derives from DataContext:
Notice that we have to check if the database exists , if not we need to create it .
In the MainPage.xaml.cs add the following code:
To sum up, in order to use local database, we need to specify the data context then create the database if it doesn’t exist.
In the coming post , we will learn how to query the database. Stay Tuned