This is the eighth article in the "Windows Phone Mango Local Database (SQLCE)" series. To get you started using the database in Windows Phone Mango, this series of short film articles will cover all the knowledge you need to know. I'll talk about using DataContext in the Windows Phone Mango Local database.
1. What is DataContext?The purpose of DataContext is to display the database to the rest of the code in an object-oriented manner. The DataContext has three important features:(1) It inherits classes from System.Data.Linq.DataContext(2) DataContext constructor must call base (connectionString) constructor (base class constructor)(3) DataContext Displays the table on the database by using the properties of type table<tentity> (example:table<city>). This table class implements Iqueriable<tentity>, and allows you to write LINQ queries to query the database. 2. How to create DataContextin order to create a local database, you first have to define DataContext and entity classes. These classes define the mapping between the object model of the data and the database schema. The object-relational capabilities of LINQ to SQL depend on the details of the mapping, and the details of the mapping are to create a relational database mapping to the corresponding DataContext.
Reference : You can look at the documentation for MSDN: http://msdn.microsoft.com/zh-cn/library/hh202860 (v=vs.92). aspxExample:
1PublicClassCountrydatacontext:datacontext2{3Public Countrydatacontext (StringconnectionString)4:Base(connectionString)5{6}78Public table<country>Countries9{10Get11{12ReturnThis. Gettable<country>();13 }14 }15 16 public Table <city> Cities17 {18 get19 {20 return this. Gettable<city> (); }22 }23}
3. How to use DataContextIt is important to check if the database exists, and if it does not exist, you must create it. See Example:
1PublicMainPage ()2{3InitializeComponent ();45using (Countrydatacontext context = new Countrydatacontext (ConnectionString)) { 7 8 if (! Context. Databaseexists ()) { // CREATE DATABASE if it does not exist11 context. CreateDatabase (); 12 }13 }14}
Now you have the context and the database has been created. You can query as in the example:
Select P;
In this article I discussed the DataContext in the Windows Phone Mango Local database and how to use them. Keep your eye on the next article.