This is the 12th 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 how to insert data in the Windows Phone Mango Local database.
inserting data into a database is a two-step process. First use the InsertOnSubmit method to add an object to DataContext, and then call DataContext's SubmitChanges method to save the data as a row in the database.
Note : Data is not actually saved to the database until SubmitChanges is called. 1. How to insert Databefore we start, let's say we have the database structure of the following two tables: Country and City
1[Table]2public class country< Span style= "color: #008080;" > 3 { 4 //... } 6 7 8 [Table] 9 public class City10 Span style= "color: #000000;" > {11 //...12}
The DataContext is as follows:
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}
In the following code example, we will demonstrate this process, explaining that the above is boxed and inserting two new relational objects (city and country) into the database. First, we create a new country instance and then add it to the context (using the InsertOnSubmit method). Next, we create a city instance, assign it to the country instance we just created, and add it to the context. Finally, we call the SubmitChanges method to save these changes to the database.
1PrivatevoidAddcity ()2{3using (countrydatacontext context =NewCountrydatacontext (ConnectionString))4{5//Create a new Country instance6 Country Country =NewCountry ();7 country. Name ="Spain";8//Add the new country to the context9Context. Countries.insertonsubmit (country);1011//Create a new city instanceCity City =NewCity ();City. Name ="Barcelona "; // assing country15 City. Country = Country; // Add the new city to the Context17 context. Cities.insertonsubmit (city); 18 19 // save changes to the Database20 context. SubmitChanges (); 21 }22}
This article I talked about inserting data in the Windows Phone Mango Local database. Keep your eye on the next article.