Mixing MVVM, Collections, SqlCompact & Mango

After reading the articles about Local Database creating local databases, the examples uses ObservableCollections, and What if I use a ICollectionView?. It works! Let’s start the example.

1. Setting the Application in pure MVVM

In the case of WP7, the applications always loads in ‘RootFrame.Content’ the MainPage so I change the code in order to be in MVVM space:

  • Create the folders for Model, ViewModel, View
  • Move the MainPage view into View Folder
  • In the Properties/WMAppManifest.xml set:

<Tasks>
<DefaultTask  Name ="_default" NavigationPage="View/MainPage.xaml"/>
</Tasks>

  • And in App.xml.cs replace the end with this:

public static MainViewModel MVM { get; set; }
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;

// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;

MVM = new MainViewModel();
MVM.MainView = RootFrame.Content as MainPage;
MVM.MainView.DataContext = MVM;
}

2. Creating the model

Create the class Model/User.cs with the following:


[Table(Name = "Users")]
public class User
{
[Column(Name = "id", IsDbGenerated = true, IsPrimaryKey = true, CanBeNull = false)]
public Int32 id;

[Column(Name = "name")]
public string Name { get; set; }

[Column(Name = "age")]
public Int32 Age { get; set; }

}

3. Creating the DataContext

and now create the sql compact datacontext (Add reference: System.Data.Linq)

I created it in Model/UsersContext.cs:


public class UsersContext : DataContext
{
public UsersContext(): base("Data Source=isostore:/Users.sdf")
{
if (DatabaseExists() == false)
{
CreateDatabase();
}
}

public Table<Model.User> Users { get { return this.GetTable<Model.User>(); } }
}

4. The viewmodel

Until here everything is standard, now comes the ViewModel where everything you know changes:


public class MainViewModel : BaseViewModel
{
public static UsersContext Context { get; set; }

public ICollectionView Users { get; set; }

#region Views
public MainPage MainView { get; set; }
#endregion

#region New User Two Way Binding Properties
private string _username;
public String UserName
{
get { return _username; }
set
{
_username = value;
Notify(() => UserName);
}
}

private Int32 _userage;
public Int32 UserAge
{
get { return _userage; }
set
{
_userage = value;
Notify(() => UserAge);
}
}
#endregion

#region Commands
public DelegateCommand InsertCommand { get;set;}
public DelegateCommand DeleteCommand { get; set; }
public DelegateCommand UpdateCommand { get; set; }
public DelegateCommand EditCommand { get; set; }
#endregion

public MainViewModel()
{
Context = new UsersContext();
Users = new CollectionViewSource() { Source = Context.Users }.View;

if (Users.IsEmpty)
{
Context.Users.InsertOnSubmit(new User() { Name = "John", Age = 30 });
Context.Users.InsertOnSubmit(new User() { Name = "Dan", Age = 20 });
Context.Users.InsertOnSubmit(new User() { Name = "Victoria", Age = 18 });
Context.SubmitChanges();
Users.Refresh();
}

InsertCommand = Commands.Create(() =>
{
Context.Users.InsertOnSubmit(new User() { Name = UserName, Age = UserAge });
Context.SubmitChanges();
Users.Refresh();
});

DeleteCommand = Commands.Create(() =>
{
if (Users.Current<User>() == null)
return;
Context.Users.DeleteOnSubmit(Users.Current<User>());
Context.SubmitChanges();
Users.Refresh();
});

EditCommand = Commands.Create(() =>
{
if (Users.Current<User>() == null)
return;
UserName = Users.Current<User>().Name;
UserAge = Users.Current<User>().Age;
});

UpdateCommand = Commands.Create(() =>
{
if (Users.Current<User>() == null)
return;
Users.Current<User>().Name = UserName;
Users.Current<User>().Age = UserAge;
Context.SubmitChanges();
Users.Refresh();
});
}
}

The most important line is the following:


Users = new CollectionViewSource() { Source = Context.Users }.View;

This line is magic because connects the ICollectionView to the database in order to make database operations.

Here you can download the example: MVVMDatabaseApp

From here now is possible to create a DataForm control, but this is another story.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s