SlideShare a Scribd company logo
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

PPTX
10 wp7 local database
PDF
FiletodbAdapters
PPTX
Ch 7 data binding
PPT
ASP.NET 08 - Data Binding And Representation
PPTX
Ch06 ado.net fundamentals
PPTX
OakTable World 2015 - Using XMLType content with the Oracle In-Memory Column...
PPTX
EclipseCon 2021 NoSQL Endgame
PPTX
Data Access Options in SharePoint 2010
10 wp7 local database
FiletodbAdapters
Ch 7 data binding
ASP.NET 08 - Data Binding And Representation
Ch06 ado.net fundamentals
OakTable World 2015 - Using XMLType content with the Oracle In-Memory Column...
EclipseCon 2021 NoSQL Endgame
Data Access Options in SharePoint 2010

What's hot (19)

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

Viewers also liked (20)

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

Similar to 10.Local Database & LINQ (20)

PPTX
Windows Phone 8 - 7 Local Database
PPT
What's New for Data?
PPTX
PPTX
Entity Framework Database and Code First
PPTX
Practical OData
PDF
SQLite in Adobe AIR
PDF
Introduction to SQLite in Adobe AIR
PDF
Local storage in Web apps
PDF
Rapid Prototyping with PEAR
PPT
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
PPTX
Introduction to RavenDB
PPTX
SQL for Web APIs - Simplifying Data Access for API Consumers
PDF
Hands On Spring Data
PPTX
ASP.NET Lecture 4
PPTX
Introducing DataWave
PDF
Rename with Confidence – Building Dynamic FileMaker Systems
PPTX
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
PDF
Requery overview
PPTX
Domain-Driven Design with SeedStack
Windows Phone 8 - 7 Local Database
What's New for Data?
Entity Framework Database and Code First
Practical OData
SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
Local storage in Web apps
Rapid Prototyping with PEAR
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
Introduction to RavenDB
SQL for Web APIs - Simplifying Data Access for API Consumers
Hands On Spring Data
ASP.NET Lecture 4
Introducing DataWave
Rename with Confidence – Building Dynamic FileMaker Systems
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Requery overview
Domain-Driven Design with SeedStack

More from Nguyen Tuan (11)

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

Recently uploaded (10)

PPTX
Introduction to Packet Tracer Course Overview - Aug 21 (1).pptx
DOC
NIU毕业证学历认证,阿比林基督大学毕业证留学生学历
PPTX
Social Media People PowerPoint Templates.pptx
PDF
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
PDF
2025 Guide to Buy Verified Cash App Accounts You Can Trust.pdf
PDF
Kids, Screens & Emotional Development by Meenakshi Khakat
PDF
Date Right Stuff - Invite only, conservative dating app
DOC
SIUE毕业证学历认证,阿祖萨太平洋大学毕业证学位证书复制
PDF
Best 4 Sites for Buy Verified Cash App Accounts – BTC Only.pdf
PPTX
ASMS Telecommunication company Profile
Introduction to Packet Tracer Course Overview - Aug 21 (1).pptx
NIU毕业证学历认证,阿比林基督大学毕业证留学生学历
Social Media People PowerPoint Templates.pptx
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
2025 Guide to Buy Verified Cash App Accounts You Can Trust.pdf
Kids, Screens & Emotional Development by Meenakshi Khakat
Date Right Stuff - Invite only, conservative dating app
SIUE毕业证学历认证,阿祖萨太平洋大学毕业证学位证书复制
Best 4 Sites for Buy Verified Cash App Accounts – BTC Only.pdf
ASMS Telecommunication company Profile

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