Using dynamic data providers, like Simple.Data, to feed into DynamicViewModel

Using Dynamic Viewmodels with Simple.Data

If you haven't checked out Mark Rendle's Simple.Data project, then you really should... but before you do, let me summarise:

Simple.Data allows you to create a connection to a data source (e.g. a SQL database), write some queries against it and get a dynamic object back.

Well, we already have a DynamicViewModel - something that implements INotifyPropertyChanged and allows us to not sweat the small details of static typing - Remember, the use case for this is where the problem domain is trivial, and we don't need the full DDD domain/model thing...

I did need to create an overload for the DynamicViewModelFactory.Create method that takes a DynamicObject as a parameter and creates a new DynamicViewModel instance, fills it with the members it finds in the inbound parameter and returns it.

It was incredibly easy to put these two things together, and the simplest possible implementation looks like this:

    public MainWindow()
    {
        InitializeComponent();

        //  Open the db connection - just use a local db to show this off...
        var db = Simple.Data.Database
            .OpenConnection(@"Data Source=(local)\SQLEXPRESS;initial catalog=FunnelWeb;integrated security=true");

        //  Simple.Data allows us to dynamically query by field; 'Entry' table has an 'Id' column, so
        //  Entry.FindById(id) will work by convention. Or witchcraft. Or something
        dynamic model = db.Entry.FindById(10);

        //  Pass the DynamicObject coming back from Simple.Data into our DVM factory to get
        //  a (notifying) dynamic ViewModel back. It will contain all the same properties as the model.
        DataContext = DynamicViewModelFactory.Create(model);
    }

Now we can bind straight to the columns in the table, like <TextBlock Text="{Binding Summary}" /> - and that's all we need. No model, no plumbing, no ceremony.

Awesome.

p.s. I hope it's obvious that you could bind directly to the 'model' coming back from Simple.Data if you didn't need the VM to notify Property changes back to the View...

dynamic xaml
Posted by: Ian Randall
Last revised: 30 Jul, 2011 11:26 p.m.

Comments

No comments yet. Be the first!

Your Comments

Used for your gravatar. Not required. Will not be public.
Posting code? Indent it by four spaces to make it look nice. Learn more about Markdown.

Preview