SlideShare a Scribd company logo
1 of 31
Download to read offline
Local Database & LINQ
Nguyen Tuan | Microsoft Certified Trainer
Agenda
 Database Support in Windows Phone OS
 LINQ to SQL
 Queries
 Inserts, updates, deletes…
 Database schema upgrades
 Performance and best practices
LINQ to SQL
Locations where apps can access data
Installation
Folder
App data
FoldersApp data
FoldersApp data
Folders
Credential
Locker
LINQ to Everything
Complex Schema
• Numerous relationships and constraints
• Example: Shopping List
• 7 tables
• 100s of records
• 5 foreign keys
ItemReferenceData
PK ItemId
ItemName
ItemDescription
FK1 CategoryId
Categories
PK CategoryId
CategoryName
Lists
PK ListId
ListName
ListItems
PK ListItemId
ListItemName
FK1 ListId
Quantity
Category
Description
FK2 StoreId
Stores
PK StoreId
StoreName
StoreLocationLat
StoreLocationLong
StoreAddressLine1
StoreAddressLine2
StoreAddressCity
StoreAddressState
StoreAddressCountry
StoryAddressZip
Favorites
PK FavoriteItemId
FavoriteItemName
FavoriteItemCategory
FavoriteItemQuantity
FavoriteItemDescription
FK1 FavoriteItemListId
FavoriteItemPhoto
History
PK HistoryItemId
HistoryItemName
HistoryItemCategory
HistoryItemQuantity
HistoryItemDescriptioin
HistoryItemDateAdded
FK1 HistoryItemListId
HistoryItemPhoto
Reference Data
• Huge amounts of static reference data
• Example: dictionary app
• 3 tables
• 1 table with 500k rows
Words
PK WordId
Word
Pronunciation
Definition
AlternateSpellings
Origin
Favorites
PK FavoriteId
FK1 WordId
History
PK HistoryItemId
FK1 WordId
AddedDate
Web Service Cache
• Fetch reference data from cloud
• Cache locally
• Combine with user-specific data
Cloud
Service
Windows Phone
Local Data Storage: Overview



Application
Settings File
App
Application
Files
Package
Manager
App Data Folder
WP7 Isolated
Storage APIs
Install
DB
Databasefile
DB Database
File (r/o)
Architecture
Custom Data
Context
App Objects
Identity
Management
Change Tracking
Update
Processing
Object
Materialization
Core ADO.NET (System.Data)
SQLCE ADO.NET Provider (System.Data.SqlServerCe)
SQLCEDB
.CallSystem.Linq.Queryable.Select( .Call
System.Linq.Queryable.Where(
.Constant(Table(Wines)),'(.Lambda #Lambda1)),
'(.Lambda#Lambda2)).Lambda
#Lambda1(db.Wines $w) { $w.Country== “USA" }
.Lambda #Lambda2(w.Country$w){ $w.Name}
var query = from w in db.Wines
where w.Country == "USA"
select w.Name;
select Name
from Wines
where Country = "USA"
Objects, Objects, Objects…
Design
time
 Create object model: wines, varietals, vineyards, etc.
 Decorate objects with attributes for persistence
Run
time
 Create DataContextreference to database
 Translate object model into a databasefile
 Submit API persists changes to DB
Database
upgrade
 Create new objects to enable new features
 Use upgrade APIs to change DB
Varietals Wines
Vineyards WineMakers
Wines
PK WineID
Name
Description
RetailPrice
FK2 VarietalID
FK1 VineyardID
Vineyards
PK VineyardID
Name
Latitude
Longitude
Country
Varietals
PK VarietalID
Name
Winemaker
PK WinemakerID
FirstName
LastName
Database Creation: Example
// Define the tables in the database
[Table]
public class Wine : INotifyPropertyChanged, INotifyPropertyChanging
{
private string wineID;
private string name;
[Column(IsPrimaryKey=true)]
public string WineID
{
get { return wineID; }
set {
InvokePropertyChanging(new PropertyChangingEventArgs("WineID"
));
wineID = value;
InvokePropertyChanged(new PropertyChangedEventArgs("WineID"))
;
}
}
[Column]
public string Name { ... }
...
}
Define Tables
Database Creation: Example
// Define the data context.
public partial class WineDataContext : DataContext
{
public Table<Wine> Wines;
public Table<Vineyard> Vineyards;
public WineDataContext(string connection) :
base(connection) { }
}
...
// Create the database from data context, using a
connection string
DataContext db = new
WineDataContext("isostore:/wineDB.sdf");
if (!db.DatabaseExists())
db.CreateDatabase();
Using SQLMetal code generator tool
• Use Visual Studio or SQL Server Management
Studio visual designers to create a SQL Server
Compact Edition 3.5 database on Dev PC
• Start a Visual Studio Command Prompt
• Run the SQLMetal tool to generate
LINQ to SQL code file
• c:>Sqlmetal /code:northwindEntities.cs
/context:NorthwindDataContext
/pluralize northwind.sdf
• Include generated code in your Windows Phone project
• Few fixes required to get it to compile
Queries: Examples
// Create the database form data context, using a connection string
DataContext db = new WineDataContext("isostore:/wineDB.sdf");
// Find all wines currently at home, ordered by date acquired
var q = from w in db.Wines
where w.Varietal.Name == “Shiraz” && w.IsAtHome == true
orderby w.DateAcquired
select w;
DB
Name Little
Penguin
Varietal Pinot Noir
AtHome False
Name Little
Penguin
Varietal Pinot Noir
AtHome True
Inserts/Updates/Deletes
• It’s all about the DataContext
• Changes made against
the DataContext first
• Changes persisted
by calling SubmitChanges()
• SubmitChanges
• LINQ to SQL determines change
set and submits to DB
Name Little
Penguin
Varietal Pinot Noir
AtHome False
Name Yellow
Tail
Varietal Pinot
Noir
AtHome True
Inserts/Updates/Deletes
Insert Update
Wine newWine = new Wine
{
WineID = “1768",
Name = “Windows Phone
Syrah",
Description = “Bold and
spicy"
};
db.Wines.InsertOnSubmit(newWine)
;
db.SubmitChanges();
Wine wine =
(from w in db.Wines
where w.WineID == “1768"
select w).First();
wine.Description = “Hints of plum
and melon";
db.SubmitChanges();
Inserts/Updates/Deletes
Delete
var vineyardsToDelete =
from Vineyards v in db.Vineyards
where v.Country == “Australia”
select v;
db.Vineyards.DeleteAllOnSubmit
(vineyardsToDelete);
db.SubmitChanges();
Demo :
DataStorage
Relationships
• Express one-many, one-one and many-many
relationships using EntitySet<T> and
EntityRef<T> columns
• In the relational database, a child table has a
column – the Foreign Key – that stores the
unique ID of a record in the parent table
Words
PK WordId
Word
Pronunciation
Definition
AlternateSpellings
Origin
Favorites
PK FavoriteId
FK1 WordId
History
PK HistoryItemId
FK1 WordId
AddedDate
Example: Parent Object
[Table]
public class Contact : INotifyPropertyChanged, INotifyPropertyChanging
{
// Fields
private EntitySet<Lead> leads = new EntitySet<Lead>();
[Association(Storage = "leads", OtherKey = "ContactID")]
public EntitySet<Lead> Leads
{
get { return this.leads; }
set {
InvokePropertyChanging(
new PropertyChangingEventArgs("Leads"));
this.leads.Assign(value);
InvokePropertyChanged(
new PropertyChangedEventArgs("Leads"));
}
}
Example: Child Object
[Table]
[Index (Name="ContactID_Idx", Columns="ContactID", IsUnique=false)]
public class Lead : INotifyPropertyChanged, INotifyPropertyChanging
{
private EntityRef<Contact> contact;
[Column]
public long ContactID {get; set; }
[Association(Storage = "contact", ThisKey = "ContactID", IsForeignKey=true)]
public Contact Contact
{
get { return this.contact.Entity; }
set {
InvokePropertyChanging(new PropertyChangingEventArgs("Contact"));
this.contact.Entity = value;
InvokePropertyChanged(new PropertyChangedEventArgs("Contact"));
if (value != null)
this.ContactID = value.ContactID;
}
}
Deletes
Delete
var contactsToDelete =
from Contact c in db.Contacts
where c.Company == “Appamundi”
select c;
db.Contacts.DeleteAllOnSubmit
(contactsToDelete);
db.SubmitChanges();
Delete Child Objects First
var contactsToDelete = from Contact c in db.Contacts
where c.Company == “Appamundi"
select c;
foreach (Contact c in contactsToDelete)
{
db.Leads.DeleteAllOnSubmit(c.Leads);
}
db.Contacts.DeleteAllOnSubmit(contactsToDelete);
db.SubmitChanges();
Demo:
SqlLiteWP8
Database Schema Upgrades
• DatabaseSchemaUpdater allows simple upgrades
on your existing DB
• Supports adding
• Tables
• Columns
• Indices
• Associations/foreign keys
• Schema updates are transactional
Database Schema Upgrades
WineDataContext wineDC = new WineDataContext(App.WineDBConnectionString);
DatabaseSchemaUpdater dsu = wineDC.CreateDatabaseSchemaUpdater();
if (dsu.DatabaseSchemaVersion == 1)
{
dsu.AddColumn<Wine>("BottleType");
dsu.DatabaseSchemaVersion = 2;
dsu.Execute();
}
Best Practices
LINQ to SQL Performance and Best Practices
• Keep change sets small
• Submit early and often to avoid data loss on app termination
• Use background threads
• Non-trivial operations will impact app responsiveness if done on UI thread
• Optimizeread-only queries
• Set ObjectTrackingEnabled to minimize memory usage
• Use secondary indices for properties which you query often
LINQ to SQL Performance and Best Practices
• Populatelarge reference data tables in advance
• Create a simple project to prepopulate data in emulator
• Pull out database file using Isolated Storage explorer
• Use the right tool for the job
• Database for large or complex data sets
• IsolatedStorageSettings or basic files for small data sets
Summary
• Database Support in Windows Phone OS
• LINQ to SQL
• Queries
• Inserts, updates, deletes…
• Database schema upgrades
• Performance and best practices

More Related Content

What's hot

2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.02005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0Daniel Fisher
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0Korhan Bircan
 
Storlets fb session_16_9
Storlets fb session_16_9Storlets fb session_16_9
Storlets fb session_16_9Eran Rom
 
Apache Olingo - ApacheCon Denver 2014
Apache Olingo - ApacheCon Denver 2014Apache Olingo - ApacheCon Denver 2014
Apache Olingo - ApacheCon Denver 2014Stephan Klevenz
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020Thodoris Bais
 
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...Marco Gralike
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow BasicsPramod Singla
 
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...SPTechCon
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.netNgeam Soly
 
Introduction to Event Sourcing and CQRS (IASA-IL)
Introduction to Event Sourcing and CQRS (IASA-IL)Introduction to Event Sourcing and CQRS (IASA-IL)
Introduction to Event Sourcing and CQRS (IASA-IL)Vladik Khononov
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jjJoe Jacob
 

What's hot (19)

For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
 
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.02005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Hibernate
HibernateHibernate
Hibernate
 
B_110500002
B_110500002B_110500002
B_110500002
 
Storlets fb session_16_9
Storlets fb session_16_9Storlets fb session_16_9
Storlets fb session_16_9
 
Apache Olingo - ApacheCon Denver 2014
Apache Olingo - ApacheCon Denver 2014Apache Olingo - ApacheCon Denver 2014
Apache Olingo - ApacheCon Denver 2014
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
 
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...
 
Core Data
Core DataCore Data
Core Data
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics
 
FREE Sql Server syllabus
FREE Sql Server syllabusFREE Sql Server syllabus
FREE Sql Server syllabus
 
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
Introduction to Event Sourcing and CQRS (IASA-IL)
Introduction to Event Sourcing and CQRS (IASA-IL)Introduction to Event Sourcing and CQRS (IASA-IL)
Introduction to Event Sourcing and CQRS (IASA-IL)
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 

Viewers also liked

Cloud Computing for Business - The Road to IT-as-a-Service
Cloud Computing for Business - The Road to IT-as-a-ServiceCloud Computing for Business - The Road to IT-as-a-Service
Cloud Computing for Business - The Road to IT-as-a-ServiceJames Urquhart
 
Революция без крови
 Революция без крови Революция без крови
Революция без кровиVadim Zhartun
 
Is Facebook involved with click frauds?
Is Facebook involved with click frauds?Is Facebook involved with click frauds?
Is Facebook involved with click frauds?Max Favilli
 
365 Constituent Engagement
365 Constituent Engagement365 Constituent Engagement
365 Constituent EngagementCharity Dynamics
 
Программа поддержки экспорта инновационной и высокотехнологичной продукции, р...
Программа поддержки экспорта инновационной и высокотехнологичной продукции, р...Программа поддержки экспорта инновационной и высокотехнологичной продукции, р...
Программа поддержки экспорта инновационной и высокотехнологичной продукции, р...Ingria. Technopark St. Petersburg
 
Multi Echelon Inventories
Multi Echelon InventoriesMulti Echelon Inventories
Multi Echelon Inventories3abooodi
 
網賺基礎
網賺基礎網賺基礎
網賺基礎waytorich
 
FATCA Compliance using Business Process and Rules Managament
FATCA Compliance using Business Process and Rules ManagamentFATCA Compliance using Business Process and Rules Managament
FATCA Compliance using Business Process and Rules ManagamentGarry Gomersall
 
The Importance of Social and Mobile in Year-End Campaigns
The Importance of Social and Mobile in Year-End CampaignsThe Importance of Social and Mobile in Year-End Campaigns
The Importance of Social and Mobile in Year-End CampaignsCharity Dynamics
 
Media Landscape (Fall 2009)
Media Landscape (Fall 2009)Media Landscape (Fall 2009)
Media Landscape (Fall 2009)Brian Hadley
 
Vizualization effect on microbres citrex
Vizualization effect on microbres citrexVizualization effect on microbres citrex
Vizualization effect on microbres citrexCITREX
 
Suzanne Pilsk Presentation to SIL Board 2012
Suzanne Pilsk Presentation to SIL Board 2012Suzanne Pilsk Presentation to SIL Board 2012
Suzanne Pilsk Presentation to SIL Board 2012Smithsonian Libraries
 
Санкт-Петербург: Меры поддержки промышленности и инноваций
Санкт-Петербург: Меры поддержки промышленности и инновацийСанкт-Петербург: Меры поддержки промышленности и инноваций
Санкт-Петербург: Меры поддержки промышленности и инновацийIngria. Technopark St. Petersburg
 
C:\fakepath\opal video slide show
C:\fakepath\opal video slide showC:\fakepath\opal video slide show
C:\fakepath\opal video slide showrobertocarneiro
 
Unit 10 Cash and fixed interest
Unit 10 Cash and fixed interestUnit 10 Cash and fixed interest
Unit 10 Cash and fixed interestAndrew Hingston
 

Viewers also liked (20)

Stoles List
Stoles ListStoles List
Stoles List
 
Cloud Computing for Business - The Road to IT-as-a-Service
Cloud Computing for Business - The Road to IT-as-a-ServiceCloud Computing for Business - The Road to IT-as-a-Service
Cloud Computing for Business - The Road to IT-as-a-Service
 
Революция без крови
 Революция без крови Революция без крови
Революция без крови
 
Is Facebook involved with click frauds?
Is Facebook involved with click frauds?Is Facebook involved with click frauds?
Is Facebook involved with click frauds?
 
365 Constituent Engagement
365 Constituent Engagement365 Constituent Engagement
365 Constituent Engagement
 
Pan Demistyfied
Pan DemistyfiedPan Demistyfied
Pan Demistyfied
 
Программа поддержки экспорта инновационной и высокотехнологичной продукции, р...
Программа поддержки экспорта инновационной и высокотехнологичной продукции, р...Программа поддержки экспорта инновационной и высокотехнологичной продукции, р...
Программа поддержки экспорта инновационной и высокотехнологичной продукции, р...
 
Papble Dedications
Papble DedicationsPapble Dedications
Papble Dedications
 
Multi Echelon Inventories
Multi Echelon InventoriesMulti Echelon Inventories
Multi Echelon Inventories
 
網賺基礎
網賺基礎網賺基礎
網賺基礎
 
Opal video slide show
Opal video slide showOpal video slide show
Opal video slide show
 
25x10 mp spb_august_2016_vostrikov_mac (1)
25x10 mp spb_august_2016_vostrikov_mac (1)25x10 mp spb_august_2016_vostrikov_mac (1)
25x10 mp spb_august_2016_vostrikov_mac (1)
 
FATCA Compliance using Business Process and Rules Managament
FATCA Compliance using Business Process and Rules ManagamentFATCA Compliance using Business Process and Rules Managament
FATCA Compliance using Business Process and Rules Managament
 
The Importance of Social and Mobile in Year-End Campaigns
The Importance of Social and Mobile in Year-End CampaignsThe Importance of Social and Mobile in Year-End Campaigns
The Importance of Social and Mobile in Year-End Campaigns
 
Media Landscape (Fall 2009)
Media Landscape (Fall 2009)Media Landscape (Fall 2009)
Media Landscape (Fall 2009)
 
Vizualization effect on microbres citrex
Vizualization effect on microbres citrexVizualization effect on microbres citrex
Vizualization effect on microbres citrex
 
Suzanne Pilsk Presentation to SIL Board 2012
Suzanne Pilsk Presentation to SIL Board 2012Suzanne Pilsk Presentation to SIL Board 2012
Suzanne Pilsk Presentation to SIL Board 2012
 
Санкт-Петербург: Меры поддержки промышленности и инноваций
Санкт-Петербург: Меры поддержки промышленности и инновацийСанкт-Петербург: Меры поддержки промышленности и инноваций
Санкт-Петербург: Меры поддержки промышленности и инноваций
 
C:\fakepath\opal video slide show
C:\fakepath\opal video slide showC:\fakepath\opal video slide show
C:\fakepath\opal video slide show
 
Unit 10 Cash and fixed interest
Unit 10 Cash and fixed interestUnit 10 Cash and fixed interest
Unit 10 Cash and fixed interest
 

Similar to 10.Local Database & LINQ

Windows Phone 8 - 7 Local Database
Windows Phone 8 - 7 Local DatabaseWindows Phone 8 - 7 Local Database
Windows Phone 8 - 7 Local DatabaseOliver Scheer
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?ukdpe
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
SQLite in Adobe AIR
SQLite in Adobe AIRSQLite in Adobe AIR
SQLite in Adobe AIRPeter Elst
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRPeter Elst
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 
Rapid Prototyping with PEAR
Rapid Prototyping with PEARRapid Prototyping with PEAR
Rapid Prototyping with PEARMarkus Wolff
 
SQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API ConsumersSQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API ConsumersJerod Johnson
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring DataEric Bottard
 
Introducing DataWave
Introducing DataWaveIntroducing DataWave
Introducing DataWaveData Works MD
 
Rename with Confidence – Building Dynamic FileMaker Systems
Rename with Confidence – Building Dynamic FileMaker SystemsRename with Confidence – Building Dynamic FileMaker Systems
Rename with Confidence – Building Dynamic FileMaker SystemsDB Services
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Sparkhound Inc.
 
Domain-Driven Design with SeedStack
Domain-Driven Design with SeedStackDomain-Driven Design with SeedStack
Domain-Driven Design with SeedStackSeedStack
 
Simple Web Development in Java
Simple Web Development in JavaSimple Web Development in Java
Simple Web Development in JavaVincent Tencé
 

Similar to 10.Local Database & LINQ (20)

Windows Phone 8 - 7 Local Database
Windows Phone 8 - 7 Local DatabaseWindows Phone 8 - 7 Local Database
Windows Phone 8 - 7 Local Database
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?
 
La sql
La sqlLa sql
La sql
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Practical OData
Practical ODataPractical OData
Practical OData
 
SQLite in Adobe AIR
SQLite in Adobe AIRSQLite in Adobe AIR
SQLite in Adobe AIR
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
Rapid Prototyping with PEAR
Rapid Prototyping with PEARRapid Prototyping with PEAR
Rapid Prototyping with PEAR
 
Introduction to RavenDB
Introduction to RavenDBIntroduction to RavenDB
Introduction to RavenDB
 
SQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API ConsumersSQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API Consumers
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring Data
 
ASP.NET Lecture 4
ASP.NET Lecture 4ASP.NET Lecture 4
ASP.NET Lecture 4
 
Introducing DataWave
Introducing DataWaveIntroducing DataWave
Introducing DataWave
 
Rename with Confidence – Building Dynamic FileMaker Systems
Rename with Confidence – Building Dynamic FileMaker SystemsRename with Confidence – Building Dynamic FileMaker Systems
Rename with Confidence – Building Dynamic FileMaker Systems
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
 
Requery overview
Requery overviewRequery overview
Requery overview
 
Domain-Driven Design with SeedStack
Domain-Driven Design with SeedStackDomain-Driven Design with SeedStack
Domain-Driven Design with SeedStack
 
Linq
LinqLinq
Linq
 
Simple Web Development in Java
Simple Web Development in JavaSimple Web Development in Java
Simple Web Development in Java
 

More from Nguyen Tuan

07.Notifications & Reminder, Contact
07.Notifications & Reminder, Contact07.Notifications & Reminder, Contact
07.Notifications & Reminder, ContactNguyen Tuan
 
12.Maps and Location
12.Maps and Location12.Maps and Location
12.Maps and LocationNguyen Tuan
 
11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA) 11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA) Nguyen Tuan
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WPNguyen Tuan
 
08.Push Notifications
08.Push Notifications 08.Push Notifications
08.Push Notifications Nguyen Tuan
 
13.Windows Phone Store
13.Windows Phone Store13.Windows Phone Store
13.Windows Phone StoreNguyen Tuan
 
06.Programming Media on Windows Phone
06.Programming Media on Windows Phone06.Programming Media on Windows Phone
06.Programming Media on Windows PhoneNguyen Tuan
 
05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & Animation05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & AnimationNguyen Tuan
 
03.Controls in Windows Phone
03.Controls in Windows Phone03.Controls in Windows Phone
03.Controls in Windows PhoneNguyen Tuan
 
04.Navigation on Windows Phone
04.Navigation on Windows Phone04.Navigation on Windows Phone
04.Navigation on Windows PhoneNguyen Tuan
 
02.Designing Windows Phone Application
02.Designing Windows Phone Application02.Designing Windows Phone Application
02.Designing Windows Phone ApplicationNguyen Tuan
 

More from Nguyen Tuan (11)

07.Notifications & Reminder, Contact
07.Notifications & Reminder, Contact07.Notifications & Reminder, Contact
07.Notifications & Reminder, Contact
 
12.Maps and Location
12.Maps and Location12.Maps and Location
12.Maps and Location
 
11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA) 11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA)
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
 
08.Push Notifications
08.Push Notifications 08.Push Notifications
08.Push Notifications
 
13.Windows Phone Store
13.Windows Phone Store13.Windows Phone Store
13.Windows Phone Store
 
06.Programming Media on Windows Phone
06.Programming Media on Windows Phone06.Programming Media on Windows Phone
06.Programming Media on Windows Phone
 
05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & Animation05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & Animation
 
03.Controls in Windows Phone
03.Controls in Windows Phone03.Controls in Windows Phone
03.Controls in Windows Phone
 
04.Navigation on Windows Phone
04.Navigation on Windows Phone04.Navigation on Windows Phone
04.Navigation on Windows Phone
 
02.Designing Windows Phone Application
02.Designing Windows Phone Application02.Designing Windows Phone Application
02.Designing Windows Phone Application
 

Recently uploaded

Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesChandrakantDivate1
 
Thane 💋 Call Girls 7738631006 💋 Call Girls in Thane Escort service book now. ...
Thane 💋 Call Girls 7738631006 💋 Call Girls in Thane Escort service book now. ...Thane 💋 Call Girls 7738631006 💋 Call Girls in Thane Escort service book now. ...
Thane 💋 Call Girls 7738631006 💋 Call Girls in Thane Escort service book now. ...Pooja Nehwal
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRnishacall1
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsChandrakantDivate1
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfCWS Technology
 
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Servicenishacall1
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsChandrakantDivate1
 

Recently uploaded (8)

Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & Examples
 
Thane 💋 Call Girls 7738631006 💋 Call Girls in Thane Escort service book now. ...
Thane 💋 Call Girls 7738631006 💋 Call Girls in Thane Escort service book now. ...Thane 💋 Call Girls 7738631006 💋 Call Girls in Thane Escort service book now. ...
Thane 💋 Call Girls 7738631006 💋 Call Girls in Thane Escort service book now. ...
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and Layouts
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdf
 
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s Tools
 

10.Local Database & LINQ

  • 1. Local Database & LINQ Nguyen Tuan | Microsoft Certified Trainer
  • 2. Agenda  Database Support in Windows Phone OS  LINQ to SQL  Queries  Inserts, updates, deletes…  Database schema upgrades  Performance and best practices
  • 4. Locations where apps can access data Installation Folder App data FoldersApp data FoldersApp data Folders Credential Locker
  • 6. Complex Schema • Numerous relationships and constraints • Example: Shopping List • 7 tables • 100s of records • 5 foreign keys ItemReferenceData PK ItemId ItemName ItemDescription FK1 CategoryId Categories PK CategoryId CategoryName Lists PK ListId ListName ListItems PK ListItemId ListItemName FK1 ListId Quantity Category Description FK2 StoreId Stores PK StoreId StoreName StoreLocationLat StoreLocationLong StoreAddressLine1 StoreAddressLine2 StoreAddressCity StoreAddressState StoreAddressCountry StoryAddressZip Favorites PK FavoriteItemId FavoriteItemName FavoriteItemCategory FavoriteItemQuantity FavoriteItemDescription FK1 FavoriteItemListId FavoriteItemPhoto History PK HistoryItemId HistoryItemName HistoryItemCategory HistoryItemQuantity HistoryItemDescriptioin HistoryItemDateAdded FK1 HistoryItemListId HistoryItemPhoto
  • 7. Reference Data • Huge amounts of static reference data • Example: dictionary app • 3 tables • 1 table with 500k rows Words PK WordId Word Pronunciation Definition AlternateSpellings Origin Favorites PK FavoriteId FK1 WordId History PK HistoryItemId FK1 WordId AddedDate
  • 8. Web Service Cache • Fetch reference data from cloud • Cache locally • Combine with user-specific data Cloud Service Windows Phone
  • 9. Local Data Storage: Overview    Application Settings File App Application Files Package Manager App Data Folder WP7 Isolated Storage APIs Install DB Databasefile DB Database File (r/o)
  • 10. Architecture Custom Data Context App Objects Identity Management Change Tracking Update Processing Object Materialization Core ADO.NET (System.Data) SQLCE ADO.NET Provider (System.Data.SqlServerCe) SQLCEDB .CallSystem.Linq.Queryable.Select( .Call System.Linq.Queryable.Where( .Constant(Table(Wines)),'(.Lambda #Lambda1)), '(.Lambda#Lambda2)).Lambda #Lambda1(db.Wines $w) { $w.Country== “USA" } .Lambda #Lambda2(w.Country$w){ $w.Name} var query = from w in db.Wines where w.Country == "USA" select w.Name; select Name from Wines where Country = "USA"
  • 11. Objects, Objects, Objects… Design time  Create object model: wines, varietals, vineyards, etc.  Decorate objects with attributes for persistence Run time  Create DataContextreference to database  Translate object model into a databasefile  Submit API persists changes to DB Database upgrade  Create new objects to enable new features  Use upgrade APIs to change DB Varietals Wines Vineyards WineMakers Wines PK WineID Name Description RetailPrice FK2 VarietalID FK1 VineyardID Vineyards PK VineyardID Name Latitude Longitude Country Varietals PK VarietalID Name Winemaker PK WinemakerID FirstName LastName
  • 12. Database Creation: Example // Define the tables in the database [Table] public class Wine : INotifyPropertyChanged, INotifyPropertyChanging { private string wineID; private string name; [Column(IsPrimaryKey=true)] public string WineID { get { return wineID; } set { InvokePropertyChanging(new PropertyChangingEventArgs("WineID" )); wineID = value; InvokePropertyChanged(new PropertyChangedEventArgs("WineID")) ; } } [Column] public string Name { ... } ... } Define Tables
  • 13. Database Creation: Example // Define the data context. public partial class WineDataContext : DataContext { public Table<Wine> Wines; public Table<Vineyard> Vineyards; public WineDataContext(string connection) : base(connection) { } } ... // Create the database from data context, using a connection string DataContext db = new WineDataContext("isostore:/wineDB.sdf"); if (!db.DatabaseExists()) db.CreateDatabase();
  • 14. Using SQLMetal code generator tool • Use Visual Studio or SQL Server Management Studio visual designers to create a SQL Server Compact Edition 3.5 database on Dev PC • Start a Visual Studio Command Prompt • Run the SQLMetal tool to generate LINQ to SQL code file • c:>Sqlmetal /code:northwindEntities.cs /context:NorthwindDataContext /pluralize northwind.sdf • Include generated code in your Windows Phone project • Few fixes required to get it to compile
  • 15. Queries: Examples // Create the database form data context, using a connection string DataContext db = new WineDataContext("isostore:/wineDB.sdf"); // Find all wines currently at home, ordered by date acquired var q = from w in db.Wines where w.Varietal.Name == “Shiraz” && w.IsAtHome == true orderby w.DateAcquired select w;
  • 16. DB Name Little Penguin Varietal Pinot Noir AtHome False Name Little Penguin Varietal Pinot Noir AtHome True Inserts/Updates/Deletes • It’s all about the DataContext • Changes made against the DataContext first • Changes persisted by calling SubmitChanges() • SubmitChanges • LINQ to SQL determines change set and submits to DB Name Little Penguin Varietal Pinot Noir AtHome False Name Yellow Tail Varietal Pinot Noir AtHome True
  • 17. Inserts/Updates/Deletes Insert Update Wine newWine = new Wine { WineID = “1768", Name = “Windows Phone Syrah", Description = “Bold and spicy" }; db.Wines.InsertOnSubmit(newWine) ; db.SubmitChanges(); Wine wine = (from w in db.Wines where w.WineID == “1768" select w).First(); wine.Description = “Hints of plum and melon"; db.SubmitChanges();
  • 18. Inserts/Updates/Deletes Delete var vineyardsToDelete = from Vineyards v in db.Vineyards where v.Country == “Australia” select v; db.Vineyards.DeleteAllOnSubmit (vineyardsToDelete); db.SubmitChanges();
  • 20. Relationships • Express one-many, one-one and many-many relationships using EntitySet<T> and EntityRef<T> columns • In the relational database, a child table has a column – the Foreign Key – that stores the unique ID of a record in the parent table Words PK WordId Word Pronunciation Definition AlternateSpellings Origin Favorites PK FavoriteId FK1 WordId History PK HistoryItemId FK1 WordId AddedDate
  • 21. Example: Parent Object [Table] public class Contact : INotifyPropertyChanged, INotifyPropertyChanging { // Fields private EntitySet<Lead> leads = new EntitySet<Lead>(); [Association(Storage = "leads", OtherKey = "ContactID")] public EntitySet<Lead> Leads { get { return this.leads; } set { InvokePropertyChanging( new PropertyChangingEventArgs("Leads")); this.leads.Assign(value); InvokePropertyChanged( new PropertyChangedEventArgs("Leads")); } }
  • 22. Example: Child Object [Table] [Index (Name="ContactID_Idx", Columns="ContactID", IsUnique=false)] public class Lead : INotifyPropertyChanged, INotifyPropertyChanging { private EntityRef<Contact> contact; [Column] public long ContactID {get; set; } [Association(Storage = "contact", ThisKey = "ContactID", IsForeignKey=true)] public Contact Contact { get { return this.contact.Entity; } set { InvokePropertyChanging(new PropertyChangingEventArgs("Contact")); this.contact.Entity = value; InvokePropertyChanged(new PropertyChangedEventArgs("Contact")); if (value != null) this.ContactID = value.ContactID; } }
  • 23. Deletes Delete var contactsToDelete = from Contact c in db.Contacts where c.Company == “Appamundi” select c; db.Contacts.DeleteAllOnSubmit (contactsToDelete); db.SubmitChanges();
  • 24. Delete Child Objects First var contactsToDelete = from Contact c in db.Contacts where c.Company == “Appamundi" select c; foreach (Contact c in contactsToDelete) { db.Leads.DeleteAllOnSubmit(c.Leads); } db.Contacts.DeleteAllOnSubmit(contactsToDelete); db.SubmitChanges();
  • 26. Database Schema Upgrades • DatabaseSchemaUpdater allows simple upgrades on your existing DB • Supports adding • Tables • Columns • Indices • Associations/foreign keys • Schema updates are transactional
  • 27. Database Schema Upgrades WineDataContext wineDC = new WineDataContext(App.WineDBConnectionString); DatabaseSchemaUpdater dsu = wineDC.CreateDatabaseSchemaUpdater(); if (dsu.DatabaseSchemaVersion == 1) { dsu.AddColumn<Wine>("BottleType"); dsu.DatabaseSchemaVersion = 2; dsu.Execute(); }
  • 29. LINQ to SQL Performance and Best Practices • Keep change sets small • Submit early and often to avoid data loss on app termination • Use background threads • Non-trivial operations will impact app responsiveness if done on UI thread • Optimizeread-only queries • Set ObjectTrackingEnabled to minimize memory usage • Use secondary indices for properties which you query often
  • 30. LINQ to SQL Performance and Best Practices • Populatelarge reference data tables in advance • Create a simple project to prepopulate data in emulator • Pull out database file using Isolated Storage explorer • Use the right tool for the job • Database for large or complex data sets • IsolatedStorageSettings or basic files for small data sets
  • 31. Summary • Database Support in Windows Phone OS • LINQ to SQL • Queries • Inserts, updates, deletes… • Database schema upgrades • Performance and best practices