Combining .NET RIA Services and MVVM in Silverlight 3.0

mvvmriasilverlightsilverlight-3.0wcf-ria-services

When using .NET RIA Services and MVVM in Silverlight 3.0 is there a difference between the Metadata type from RIA Services and the ViewModel from the MVVM pattern? Are these the same thing or should they be keep separate?

The metadata type is a sealed internal class to the partial Entity class. There doesn't seem to be a proper separation there but the metadata type can also be decorated with attributes for Validation which makes it look like a ViewModel.

I've searched around but I didn't see anything that talks about this in any detail.

Best Answer

Agree with ChuckJ - generally the DomainContext forms part of a view model. For example, say I had a search page that allowed searching against a product catalog. Here is how I'd structure things:

On the server:

class Catalog : DomainService {
    IQueryable<Product> GetProducts(string keyword) { ... }
}

The generated DomainContext:

class Catalog : DomainContext {
    EntityList<Product> Products { get; }
    void LoadProducts(string keyword);
}

The view model I would write:

class SearchViewModel {
    Catalog _catalog = new Catalog();

    public IEnumerable<Product> Results {
        get { return _catalog.Products; }
    }

    public void Search(string keyword) {
        _catalog.Products.Clear();
        _catalog.LoadProducts(keyword);
    }
}

And then finally in my xaml, I'd set my UserControl's DataContext to be an instance of SearchViewModel, and bind an ItemsControl to the Results property. I'd use the ViewModel pattern of your choice to bind a button click to Search (which is effectively a command that SearchViewModel exposes). I personally like something that I have working with Silverlight.FX as in:

<Button Content="Search"
  fxui:Interaction.ClickAction="$model.Search(keywordTextBox.Text)" />

and as initially shown here.

As Chuck mentions I might indeed have other state in my view model, for example, the SelectedProduct that might be two-way bound to the SelectedItem of a ListBox in my xaml, and then bind the same SelectedProduct as the DataContext of a DataForm to show details of a selected product.

Hope that helps! I'll be blogging about this some more on my blog soon.

Related Topic